[英]Regex help to extract value from string
I can't figure out how to extract specific numbers with a specific match from a string. 我不知道如何从字符串中提取具有特定匹配项的特定数字。
Example: 例:
string myString = "blah blah **[10]** blah **[20]** and some more blah **[30]**";
Regex myIDsReg = new Regex(@"\*\*\[(\d+)\]\*\*");
Apparently the regex is sound. 显然正则表达式是声音。
Match myMatch = myIDsReg.Match(myString);
Yields "**[10]**" but nothing else. 产生“ ** [10] **”,但仅此而已。
I can't figure out how to get an array with the following values: 10, 20, 30 我不知道如何获取具有以下值的数组:10、20、30
I would do this 我会这样做
string myString = "blah blah **[10]** blah **[20]** and some more blah **[30]**";
Regex myIDsReg = new Regex(@"\*\*\[(\d+)\]\*\*");
string[] regexResult = (from Match match in myIDsReg.Matches(myString) select match.Groups[1].Value).ToArray();
You can select which output you want as well 您也可以选择想要的输出
List<string> regexResult = (from Match match in myIDsReg.Matches(myString) select match.Groups[1].Value).ToList();
or 要么
IEnumerable<string> regexResult = (from Match match in myIDsReg.Matches(myString) select match.Groups[1].Value);
I'd prefer one of the two latter 我更喜欢后者的两个
Trikks came up with the best answer. Trikks提出了最佳答案。 I just had to modify it a little to work best for me.
我只需要对其稍作修改就可以对我最好。
string myString = "blah blah **[10]** blah **[20]** and some more blah **[30]**";
Regex myIDsReg = new Regex(@"\*\*\[(\d+)\]\*\*");
string[] regexResult = (from Match match in myIDsReg.Matches(myString) select match.Groups[1].Value).ToArray();
I basically replaced "select match.Value" with "select match.Groups[1].Value". 我基本上将“ select match.Value”替换为“ select match.Groups [1] .Value”。
Thanks for your help! 谢谢你的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.