问题描述
我需要编写正则表达式的帮助,该正则表达式将从以下字符串中获取值...
我需要尝试从此文本字符串中获取数字002. SysParaI是标识符.例如,当我看到"SysParaI"时,需要在下面的括号(002)中获取数字吗?
STRING [261]目录(\ FTP \ OSP_003 \)
STRING [9] FileName(SysParaI)
STRING [4] FileExtension(002)
I need help writing a regex that will get the value out off the following string...
I need to try to get the number 002 out of this text string. SysParaI is the identifier. For example when I see "SysParaI" I need to grab the number in the following paren (002)?
STRING[261] Directory(\FTP\OSP_003\)
STRING[9] FileName(SysParaI)
STRING[4] FileExtension(002)
推荐答案
Regex r = new Regex(@"\(.*\)");
var e = r.Matches(s);
e是匹配项的集合,并且将包含()"
不会重发
e is a collection of matches, and will include the "()"
Will not requer
Regex r = new Regex(@"\((.*)\)");
var e = r.Match(s);
e.Groups将包含所有匹配项,第二项将是您的结果
e.Groups will contain all matches, the second item will your result
string text = @"STRING[261] Directory(\FTP\OSP_003\)\nSTRING[9] FileName(SysParaI)\nSTRING[4] FileExtension(002)";
Match match = Regex.Match(text, @"(?<=\(SysParaI\)[^)(]*\()\d+(?=\))",
RegexOptions.CultureInvariant);
if (match.Success)
Console.WriteLine (match.Value);
//Output
//002
可以在这里进行测试 http://regexhero.net/tester/ [ ^ ]
如果002和/或SysParaI类似于( SysParaI ) ( 002 )
,则上面的模式does not match
.
为了在这种情况下匹配,可以使用以下模式.(?<=\(\s*SysParaI\s*\)[^)(]*\(\s*)\d+(?=\s*\)
It can be tested here http://regexhero.net/tester/[^]
The above pattern does not match
if there are spaces
around 002 and/or SysParaI like ( SysParaI ) ( 002 )
.
To match in such case the following pattern can be used.(?<=\(\s*SysParaI\s*\)[^)(]*\(\s*)\d+(?=\s*\)
这篇关于帮助正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!