帮助正则表达式 [英] Help with a Regular Expression

查看:133
本文介绍了帮助正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写正则表达式的帮助,该正则表达式将从以下字符串中获取值...

我需要尝试从此文本字符串中获取数字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 with prefix and suffix options of Regex 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(请参阅有关
If this is a single string, I would think "SysParaI\).*?\((\d+)\)" should work, if you set RegexOptions.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆