简体   繁体   English

正则表达式(.NET)-如何匹配在字符串末尾包含可变位数的模式?

[英]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.

相关问题 如何使用正则表达式在一串数字的末尾返回一些数字 - How can I use a Regular Expression to return a number of numbers at the end of a string of digits 我如何用正则表达式检查字符串,该字符串包含12个字符并包含0-9a-f? - How I can check a string with Regular expressions about the string has 12 characters and contains 0-9a-f? 如何用正则表达式替换字符串? - How can I replace string with regular expressions? 如何使用正则表达式与多行模式中间包含特定文本的文本不匹配? - How to not match against text that contains specific text in the middle of a multiline pattern using regular expressions? 正则表达式:确定字符串是数字还是变量 - Regular Expressions: Determining if a String is either a number or variable 如何将HTML元素与正则表达式匹配? - How can I match HTML elements with regular expressions? 如何将嵌套表达式的内部表达式与正则表达式匹配? - How can i match inner expression on nested expression with regular expressions? .NET正则表达式 - 更短的匹配 - .NET Regular Expressions - Shorter match .NET正则表达式如何匹配在特定位置不包含单词的字符串 - .NET regular expressions how to match a string that does not contain a word at a specific position 如何匹配正则表达式中包含^的字符串? - How to match string that contains ^ in regular expression?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM