帮助正则表达式 [英] Help with a Regular Expression
问题描述
我需要编写正则表达式的帮助,该正则表达式将从以下字符串中获取值...
我需要尝试从此文本字符串中获取数字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)
推荐答案
您可以轻松而又
You can go simple and just
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
我认为与Regex
的prefix and suffix
选项匹配可以用于仅提取所需的值如下所示:
I think the matching withprefix and suffix
options ofRegex
can be used to extract only the required value from the parentheses as shown below:
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/ [
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*\)
如果这是一个字符串,那么我认为"SysParaI\).*?\((\d+)\)"
应该可以工作,如果您设置了RegexOptions.Multiline
(请参阅有关 ^ ])
如果每一行都是它自己的字符串,请检查上一行是否存在SysParaI,然后使用"\((\d+)\)
If this is a single string, I would think"SysParaI\).*?\((\d+)\)"
should work, if you setRegexOptions.Multiline
(see more about that here[^])
If each line is it''s own string, check the previous one for the presence of SysParaI then use"\((\d+)\)
这篇关于帮助正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!