29

I've got a string that may or may not contain a number of 4 or 5 digits. I'm looking for a regex that can detect if the string does in fact have such a number.

2
  • 8
    +1: Don't know why this question was downvoted. Maybe some of the l33t sooper h@><0rz on this site thought was too far below them to merit an answer, even though the FAQ on this site says that no question is "too simple" to ask... Commented Apr 3, 2009 at 13:07
  • Why not use a for loop? Commented Sep 18, 2014 at 15:35

7 Answers 7

23

The foolproof one to avoid longer numbers would be:

([^\d]|^)\d{4,5}([^\d]|$)

I'm assuming you don't want to allow for a comma after the thousands digit? If you do then:

([^\d]|^)\d{1,2},\d{3}([^\d]|$)
Sign up to request clarification or add additional context in comments.

Comments

8

Perhaps

\d{4,5}

?

Comments

4

\d{4,5} will also find strings with 6 digit numbers in - I don't know whether that's a problem or not. You might want to do something like this:

([^\d]+|^)\d{4,5}[^\d]

1 Comment

Thanks for the accept, but there are better answers than this now
2

You can also use negative look-ahead and look-behinds to do this:

 (?<!\d)\d{4,5}(?!\d)

Looking for 4-5 digits which are not preceded or followed by other digits.

This has the additional advantage of matching the 4-5 digit number in strings like e.g. asdsad1as12316asd which contain shorter numbers. It has the disadvantage of matching all 4-5 digit numbers in a string which may not be what is needed.

Comments

1

Simple \d{4,5} will suffice.

1 Comment

Sometimes we need end anchor. So it is possible: \d{4,5}$
1

.NET? Then it's [0-9]{4,5}

2 Comments

Right. I'm not much of a Regexp guy, so I don't remember character classes. [0-9] is easier. :D
This solution will kind of fail, if you have a nine number digit. It will match the first five but also the second four.
-3

It is a sudocode dont copy and paste it, it will be helpful while checking the string, does it contains numbers or not.

 if(str.matches(".*\\d+.*")) 
   print "contains numbers ";
 else 
   Print "doesn't contain numbers ";

1 Comment

This does not match numbers of exactly 4-5 digits but rather any number. It also assumes a programming language which may not be what was used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.