从字符串中获取一个恰好x位数字的数字 [英] Get a number with exactly x digits from string
问题描述
我正在寻找一个正则表达式模式,该模式与长度恰好为x的数字(例如x为2-4)匹配,并且没有其他匹配项.
im looking for a regex pattern, which matches a number with a length of exactly x (say x is 2-4) and nothing else.
示例:
"foo.bar 123 456789"
,"foo.bar 456789 123"
," 123"
,"foo.bar123 "
只必须匹配"123"
"foo.bar 123 456789"
, "foo.bar 456789 123"
, " 123"
, "foo.bar123 "
has to match only "123"
所以.只能是数字,不能有空格,字母或其他东西.
So. Only digits, no spaces, letters or other stuff.
我该怎么做?
我想在c#中使用Regex.Matches()函数提取此2-4位数字,并在其他代码中使用它.
I want to use the Regex.Matches() function in c# to extract this 2-4 digit number and use it in additional code.
推荐答案
后跟{m,n}
的任何模式都允许该模式发生m到n次.因此,对于您所需的m和n值,在\d{m,n}
中.如果必须完全是整数,请使用\d{m}
Any pattern followed by a {m,n}
allows the pattern to occur m to n times. So in your case \d{m,n}
for required values of m and n. If it has to be exactly an integer, use\d{m}
如果要在x123y中匹配123,而不要在1234中匹配,请使用\d{3}(?=\D|$)(?<=(\D|^)\d{3})
If you want to match 123 in x123y and not in 1234, use \d{3}(?=\D|$)(?<=(\D|^)\d{3})
前瞻性地确保3位数字之后的字符完全不是数字,而后方确保3位数字之前的字符完全是非数字或什么都没有.
It has a look ahead to ensure the character following the 3 digits is a non-digitornothing at all and a look behind to ensure that the character before the 3 digits is a non-digit or nothing at all.
这篇关于从字符串中获取一个恰好x位数字的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!