Get a number with exactly x digits from string

2019-08-20 23:00发布

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.

2条回答
聊天终结者
2楼-- · 2019-08-20 23:38

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.

查看更多
相关推荐>>
3楼-- · 2019-08-20 23:45

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

查看更多
登录 后发表回答