gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:58:59 25 4
gpt4 key购买 nike

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

例如:下面的文字在c#中被捕获到一个字符串中

CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
Initializing.
jsdns jsdnjs wuee uwoqw duwhduwd 9-8 is = COM10
uuwe sodks asjnjx

在上面的代码中,我想提取 COM10。同样这个值也可以更改为 COM12 或 COM8 或 COM15。我将始终在文本中包含 COM,但后面的数字可以更改。

谁能告诉我如何使用正则表达式。我使用了 RegexOptions.Multiline 但我不确定如何去做。另外,如果包含解释,那将会很有帮助。

最佳答案

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

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

解释:

\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

Working Demo

关于c# - 使用正则表达式从字符串中提取单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25277283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com