我有c#代码,其中我使用命令行运行perl文件并在c#字符串中捕获该输出。我想使用正则表达式从该字符串中提取某个单词。我尝试了几种捕获特定单词的方法,但它没有用。
例如:下面的文字是在c#
的字符串中捕获的CMD.EXE以上述路径作为当前目录启动。
不支持UNC路径。默认为Windows目录。
初始化。
jsdns jsdnjs wuee uwoqw duwhduwd 9-8 = COM10
uuwe sodks asjnjx
在上面的代码中我想提取COM10。同样,该值也可以更改为COM12或COM8或COM15。我将在文本中始终使用COM,但后续编号可以更改。
有人可以告诉我如何使用正则表达式。我使用了RegexOptions.Multiline,但我不确定如何去做。如果包含解释,也会有所帮助。
答案 0 :(得分:5)
您可以使用以下正则表达式。
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
答案 1 :(得分:1)
string thestring = @"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";
string matchedString = Regex.Match(thestring,@"COM[\d]+").Value;
与字符串(COM[\d]+
)匹配的正则表达式意味着:
匹配一个COM实例,后跟至少一个数字实例(+
)
这假设您的字符串中只有一个COM(NUMBER)实例。
你也可以放一个空格,以确保正则表达式只匹配空格COM,如下所示:
\d
答案 2 :(得分:1)