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.
-
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...Juliet– Juliet2009-04-03 13:07:20 +00:00Commented Apr 3, 2009 at 13:07
-
Why not use a for loop?Mikhail– Mikhail2014-09-18 15:35:34 +00:00Commented Sep 18, 2014 at 15:35
7 Answers
\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
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
Simple \d{4,5} will suffice.
1 Comment
.NET? Then it's [0-9]{4,5}
2 Comments
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 ";