一、忽略匹配优先模式
- *? 重复任意次,但尽可能少重复
- +? 重复1次或更多次,但尽可能少重复
- ?? 重复0次或1次,但尽可能少重复
- {n,m}? 重复n到m次,但尽可能少重复
- {n,}? 重复n次以上,但尽可能少重复
【例二】在满足匹配时,匹配尽可能长的字符串,默认情况下,采用匹配优先。
string pattern1 = @"a.*c"; // greedy match
Regex regex = new Regex(pattern1);
regex.Match("abcabc"); // return "abcabc"
【例三】使用忽略匹配优先
string pattern1 = @"a.*?c"; // non-greedy match
Regex regex = new Regex(pattern1);
regex.Match("abcabc"); // return "abc"
【例三】使用忽略匹配优先及环视
string source = "https<B>billes kites is</B> kl <B>uoioasd <B> asdf</B>uo</B>cs";
Regex reg = new Regex("<B>.*</B>",RegexOptions.IgnoreCase);
string res = reg.Match(source).Value;
Console.WriteLine(res);//打印<B>billes kites is</B> kl <B>uoioasd <B> asdf</B>uo</B>
///下面使用环视就可以不使用忽略匹配优先了//
source = "<B>uoioasd <B> asdf</B>uo</B>cs";
reg = new Regex("<B>((?!</B>).)*</B>", RegexOptions.IgnoreCase);//环视,不出现</B>
res = reg.Match(source).Value;
Console.WriteLine(res);//打印<B>uoioasd <B> asdf</B>
reg = new Regex("<B>((?!</B>).)*</B>", RegexOptions.IgnoreCase);//环视,不出现</B>及<B>
res = reg.Match(source).Value;
Console.WriteLine(res);//打印<B> asdf</B>
二、Matches函数
在输入字符串中搜索正则表达式的所有匹配项并返回所有匹配。
重载列表:
【例一】
mc = Regex.Matches(affiliationString, "<span style=\"margin:0 5px 0 0\">.*?</td>",
RegexOptions.Singleline); // affiliationString为查找的字符串
string affiliation = "";
foreach (Match item in mc)
{
if (item.Value.Length > 1)
{
affiliation += item.Value + ";";
}
}
三、IsMatch函数
指示 Regex 构造函数中指定的正则表达式在指定的输入字符串中是否找到了匹配项。
【例一】
Regex reg = new Regex("^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$");//网址格式
if (!reg.IsMatch(this.txtUrl.Text.Trim(), 0))
{
MessageBox.Show("请输入正确网址!");
return;
}
四、分组
分组注意事项:分组0是整个正则表达式匹配到的结果,然后依次是未命名分组。
例如:
(\w)(?<Num>\d+)(\s+)
1 3 2
特殊的Replacement处理
Regex.Replace方法和Match.Result方法都可以接收能够进行特殊处理的replacement字符串。下面的字符序列会被匹配到的文本所替换:
字符序列 替换内容
$& 整个表达式匹配的文本,相当于$0
$1 $2 对应编号的捕获分组所匹配的文本
${name} 对应命名捕获分组匹配的文本
$‘ 目标字符串中匹配文本之前的文本
$' 目标字符串中匹配文本之后的文本
$$ 单个$字符($1的显示为$$!)
$_ 正则原始目标字符串的副本
$+ .NET中表示最后的那个捕获型括号匹配的文本
【示例】
string source = "au.https://123.26.80.11/cs.com/index.aspx";
Regex reg = new Regex(@"https[\D]+(?<number>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/(?<domain>[^\.]+)[^/]+/([^\s$]+)", RegexOptions.IgnoreCase);
Match tmp = reg.Match(source);
if (tmp.Success)//匹配成功
{
string res = reg.Match(source).Groups["number"].Value;
Console.WriteLine(res);//打印123.26.80.11
res = reg.Match(source).Groups["domain"].Value;
Console.WriteLine(res);//打印cs
res = reg.Match(source).Groups[1].Value;
Console.WriteLine(res);//打印index.aspx
}