日期:2014-05-18  浏览次数:20721 次

请教正则表达式
要求是匹配不在括号内的字符
比如source="12ab(34cd)56e(fg78)h"
要匹配的result="abeh"


------解决方案--------------------
分两步,第一去掉括号中的内容,第二匹配特定字符。
C# code
string source = "12ab(34cd)56e(fg78)h";
source = Regex.Replace(source, @"(\([^\)]*\))", "");

foreach (Match vMatch in Regex.Matches(source, "[a-z]"))
{
    Console.WriteLine(vMatch.Value);
}

------解决方案--------------------

(?<T1>[^\(\)]*)(?:(?=\()|(?<=\)))(?<T2>[^\(\)]*)
Class中再动态的加入自己的匹配字符
------解决方案--------------------
C# code
(?<!\([^\)]*?)[a-z]+

------解决方案--------------------
(?<Result>\w*)([\(]\w*[\)])*
string source = txtSource.Text;
MatchCollection mc = null;
Regex re = null;
re = new Regex(@"(?<Result>\w*)([\(]\w*[\)])*", RegexOptions.IgnoreCase);
mc = re.Matches(source);
string r = String.Empty;
foreach (Match m in mc)
{
r += m.Groups["Numbers"].Value;
}
txtResult.Text = r;
直接测试就可以了