首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

请问正则表达式

2012-02-08 
请教正则表达式要求是匹配不在括号内的字符比如source12ab(34cd)56e(fg78)h要匹配的resultabeh[解决

请教正则表达式
要求是匹配不在括号内的字符
比如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;
直接测试就可以了

热点排行