使用正则表达式从字符串中提取单词

pha*_*ays 2 c# regex string

我有c#代码,其中我使用命令行运行perl文件并在ac#string中捕获该输出.我想使用正则表达式从该字符串中提取某个单词.我尝试了几种捕获特定单词的方法,但它没有用.

例如:下面的文本是在c#中的字符串中捕获的

CMD.EXE以上面的路径作为当前目录启动.
不支持UNC路径.默认为Windows目录.
初始化.
jsdns jsdnjs wuee uwoqw duwhduwd 9-8 is = COM10
uuwe sodks asjnjx

在上面的代码中我想提取COM10.同样,该值也可以更改为COM12或COM8或COM15.我将始终在文本中使用COM,但后续编号可以更改.

有人可以告诉我如何使用正则表达式.我使用了RegexOptions.Multiline,但我不确定如何去做.此外,如果包含解释,它将是有帮助的.

hwn*_*wnd 5

您可以使用以下正则表达式.

Match m = Regex.Match(input, @"\b(?i:com\d+)");
if (m.Success)
    Console.WriteLine(m.Value); //=> "COM10"
Run Code Online (Sandbox Code Playgroud)

说明:

\b       # the boundary between a word character (\w) and not a word character
(?i:     # group, but do not capture (case-insensitive)
  com    #   'com'
  \d+    #   digits (0-9) (1 or more times)
)        # end of grouping
Run Code Online (Sandbox Code Playgroud)

工作演示