VB.Net 正则匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24857758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:52:37  来源:igfitidea点击:

VB.Net regex matching

regexvb.net

提问by Keirathi

Okay, lets say I have a string "The cat in the hat dog", and I know want to regex match cat and dog from the same string.

好的,假设我有一个字符串“The cat in the hat dog”,我知道想要正则表达式匹配来自同一字符串的 cat 和 dog。

So I have something like:

所以我有类似的东西:

Dim myString As String = "The cat in the hat dog"
Dim regex = New Regex("\bcat\b.*\bdog")
Dim match = regex.Match(myString)
If match.Success Then
    Console.WriteLine(match.Value)
End If

The match.Value returns "cat in the hat dog", which is expected.

match.Value 返回“cat in the hat dog”,这是预期的。

But what I really need is to just "cat dog" without the other words in the middle, and I'm stuck.

但我真正需要的是“猫狗”,中间没有其他词,我被卡住了。

Thanks for any help!

谢谢你的帮助!

If it helps, the string I'm trying to parse is something like "Game Name 20_03 Starter Pack r6" and I'm trying to pull "20_03 r6" out as version information. Currently using "\b\d{2}_\d{2}\b.\br\d" as my regex string.

如果有帮助,我试图解析的字符串类似于“游戏名称 20_03 入门包 r6”,我试图将“20_03 r6”作为版本信息提取出来。目前使用 "\b\d{2}_\d{2}\b. \br\d" 作为我的正则表达式字符串。

回答by Ry-

You can parenthesize parts of your regular expression to create groups that capture values:

您可以将正则表达式的部分括起来以创建捕获值的组:

Dim regex As New Regex("\b(cat)\b.*\b(dog)")

Then use match.Groups(1).Valueand match.Groups(2).Value.

然后使用match.Groups(1).Valuematch.Groups(2).Value

回答by Avinash Raj

Your regex would be,

你的正则表达式是,

Dim regex = New Regex("\bcat\b|\bdog\b")

This matches the string cator dogin the input string.

这匹配字符串catdog输入字符串。

DEMO

演示

For the second string, your regex would be

对于第二个字符串,您的正则表达式将是

\b\d{2}_\d{2}\b|r\d

DEMO

演示

Explanation:

解释:

  • \bMatches the word boundary(ie, matches between a word character and a non-word character).
  • \d{2}Matches exactly a two digit number.
  • _Matches a literal underscore symbol.
  • \d{2}Matches exactly a two digit number.
  • \bMatches the word boundary(ie, matches between a word character and a non-word character).
  • |Logical OR operator usually used to combine two regex patterns.this|that, this or that.
  • r\dLiteral r followed by a single digit.
  • \b匹配单词边界(即单词字符和非单词字符之间的匹配)。
  • \d{2}正好匹配一个两位数。
  • _匹配文字下划线符号。
  • \d{2}正好匹配一个两位数。
  • \b匹配单词边界(即单词字符和非单词字符之间的匹配)。
  • |逻辑 OR 运算符通常用于组合两个正则表达式模式。this|that, 这个或那个。
  • r\d文字 r 后跟一个数字。