[英]Regular Expressions (.NET) - How can I match a pattern that contains a variable number of digits at the end of the string?
string src = "portfolio1, portfolio2, portfolio20, portfolio300";
I'd like to match all strings that are of the pattern @"portfolio\\d" where \\d can be anywhere from 1-3 digits in length. 我想匹配所有格式为@“ portfolio \\ d”的字符串,其中\\ d的长度可以是1-3位数。 I have read that the use of {a, b} should work, so I tried:
我已经读过使用{a,b}应该可以,所以我尝试:
pattern = @"portfolio\d{1, 3}"
Searching in the string, src, for this pattern returned an empty set. 在字符串src中搜索此模式将返回一个空集。 the following patterns worked partially:
以下模式部分起作用:
pattern = @"portfolio\d"
pattern = @"portfolio\d{1}"
Try this: 尝试这个:
pattern = @"portfolio\d{1,3}"
Note that you should not put a space in between the brackets, as you have in your example. 请注意,不要像示例中那样在方括号之间放置空格。 That's why it didn't work right.
这就是为什么它不能正常工作的原因。
Running pattern "portfolio\\d{1,3}" in Expresso, I get 4 matches on each of the portfolios. 在Expresso中运行模式“ portfolio \\ d {1,3}”,我在每个投资组合上获得4个匹配项。 The space did it was the key.
空间是关键。
String pattern = @"^(?:(?:portfolio\d{1,3})(?:\x2C\s)*)+$";
My attempt. 我的尝试。 Will match any number of comma-seperated
portfolio\\d{1,3}
's 将匹配任意数量的逗号分隔的
portfolio\\d{1,3}
的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.