Get a number with exactly x digits from string

时光怂恿深爱的人放手 提交于 2019-12-13 06:21:05

问题


im looking for a regex pattern, which matches a number with a length of exactly x (say x is 2-4) and nothing else.

Examples:

"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.

How do I have to do it?

EDIT: I want to use the Regex.Matches() function in c# to extract this 2-4 digit number and use it in additional code.


回答1:


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}

If you want to match 123 in x123y and not in 1234, use \d{3}(?=\D|$)(?<=(\D|^)\d{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.




回答2:


You can achieve this with basic RegEx:

\b(\d\d\d)\b or \b(\d{3})\b - for matching a number with exactly 3 digits

If you want variable digits: \b(\d{2,4})\b (explained demo here)
If you want to capture matches next to words: \D(\d{2,4})\D (explained demo here)

\b is a word boundary (does not match anything, it's a zero-match character)
\d matches only digits
\D matches any character that is NOT a digit
() everything in round brackets will capture a match



来源:https://stackoverflow.com/questions/15311619/get-a-number-with-exactly-x-digits-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!