正则表达式显示搜索字符

时间:2015-06-25 14:49:30

标签: regex vb.net

linqpad中的以下vb语句

Dim userAgent As String = "Mozilla/5.0 (Windows NT 6.1; WOW64)"
 Dim pattern As String = "\(([^\]]+)\;"
 Dim regex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(pattern)
 Dim operatingSystem As Match = regex.Match(userAgent)
 operatingSystem.Value.Dump()

输出为(Windows NT 6.1;

这个正则表达式是否有办法从结果匹配中省略(;

3 个答案:

答案 0 :(得分:1)

在这种情况下,环顾四周会很有用。

(?<=\()[^\]]+(?=;)

Regex Demo

查看断言不会消耗任何字符。因此,匹配的字符串中不存在(;

答案 1 :(得分:1)

只需访问第一个捕获的组:

operatingSystem.Groups(1).Value

您可以按照以下方式改进模式:

Dim pattern As String = "\(([^;]+)"

答案 2 :(得分:0)

如果您不需要匹配,请使用环视,但只检查以下内容:

Dim userAgent As String = "Mozilla/5.0 (Windows NT 6.1; WOW64)"
Dim pattern As String = "(?<=\()[^\]]+(?=;)"
Dim regex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(pattern)
Dim operatingSystem As Match = regex.Match(userAgent)
Dim resulting_value As String = operatingSystem.Value

enter image description here

REGEX EXPANATION

  • (?<=\() - 在...之前检查(的正面观察......
  • [^\]]+ - 除] ...
  • 以外的1个或多个字符
  • (?=;) - 后跟;

注意在.NET中,你甚至不必在字符类的最后位置转义],所以即使(?<=\()[^]]+(?=;)也会这样做。