我有c#代码,在其中我使用命令行运行一个perl文件,并以c#字符串捕获输出。我想使用regex从这个字符串中提取一个特定的单词。我尝试了几种方法来捕捉这个特定的单词,但是它没有起作用。
例如:下面的文本是在c#中的字符串中捕获的
CMD.EXE是从上面的路径启动的,因为不支持当前的directory.UNC路径。默认为Windows directory.Initializing.jsdns jsdnjs wuee uwoqw duwhduwd 9-8 is = COM10uuwe sodks asjnjx
在上面的代码中,我想提取COM10。类似地,此值也可以更改为COM12、COM8或COM15。我将永远在文本中COM,但后面的号码可以改变。
有人能让我知道如何使用regex吗。我用了RegexOptions.Multiline,但不知道该怎么做。此外,如果包括一个解释,这将是有帮助的。
发布于 2014-08-13 03:07:15
您可以使用以下正则表达式。
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
工作演示
发布于 2014-08-13 02:59:24
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]+
)匹配的Regex表示:
匹配COM实例和至少一个数字实例(+
) (\d
)
这是假设您的字符串中只有一个COM(NUMBER)实例。
您还可以放置一个空格以确保只有空格COM与Regex匹配,如下所示:
string matchedString = Regex.Match(thestring,@"\sCOM[\d]+").Value;
发布于 2014-08-13 03:21:09
您可以使用这样的正则表达式:
\b(COM\d+)\b
工作演示
https://stackoverflow.com/questions/25277283
复制相似问题