简体   繁体   English

正则表达式从字符串中获取值

[英]regex to get value from string

Im trying to get value from string 1-1:0.0.0(123123) Here is code 我试图从字符串1-1:0.0.0(123123)获取值这是代码

string str = "\r\n1-1:0.0.0(123123)\r\n";
string patt = @"1-1:0.0.0(\(.*?)\)\s";
Match match = Regex.Match(str, patt,RegexOptions.IgnoreCase);
string v = match.Groups[1].Value;

problem is that i dont get clear value = "(123123" 问题是我没有得到明确的价值= "(123123"
can someone explain why there is round bracket at beginning ? 有人可以解释为什么一开始会有圆括号吗? :/ :/

Your opening-round-bracket match \\( is inside the start of your capture group ( . 您的首个圆括号匹配\\(位于捕获组(的开始)

Replace (\\( with \\(( . (\\(替换为\\((

Also replace 0.0.0 with 0\\.0\\.0 for good measure. 另外,也0.0.0替换为0\\.0\\.0

The escaping of the parenthesis is not correct. 圆括号的转义是不正确的。

Change your pattern to the following (note that the backslash is in front of the first opening ( ): 将模式更改为以下格式(请注意,反斜杠位于第一个开口( )的前面:

@"1-1:0.0.0\((.*?)\)\s";

Your escape character (\\( is misplaced: 您的转义字符(\\(放错位置:

Please try following 请尝试以下

string str = "\r\n1-1:0.0.0(123123)\r\n";
string patt = @"1-1:0.0.0\((.*?)\)\s";
Match match = Regex.Match(str, patt, RegexOptions.IgnoreCase);
string v = match.Groups[1].Value;

This will print 这将打印

123123

Your capturing group is (\\(.*?) , that is a pair of parentheses which creates the capturing group, with a content of \\(.*? - matching a literal opening parenthesis and a non-greedy sequence of any characters. 您的捕获组是(\\(.*?) ,这是一对括号,它们创建捕获组,其内容为\\(.*? -匹配一个文字开头的括号和任何字符的非贪婪序列。

Also note that the . 另请注意. characters in your pattern are not matching literal dots, but any character, I point this out since the target string seems to contain dots. 模式中的字符与文字点不匹配,但是与任何字符都不匹配,我指出这一点是因为目标字符串似乎包含点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM