Regular expression to match hyphenated number ranges
This is maddeningly simple, but I am still stumped as to whether my answer is right.
I want to match a string with following format:
- 70-60
- 50-40
- 100-90
- etc.....
I just started learning about regexes today, and I worked out the following pattern to match the string:
/^[0-9]+-[0-9]+/$
But upon testing it in an online regex testing tool, I found that it doesn't match.
Any pointers that would help开发者_如何学JAVA me? Thanks a lot in advance.
the $
needs to be within the regex
/^[0-9]+-[0-9]+$/
how about:
\A[0-9]+\s*\-\s*[0-9]+\Z
NOTES:
- used
\A
and\Z
instead of^
and$
- added
\s*
to account for possible spaces
You're a bit off on the regular expression syntax. What you want is:
/^[0-9]+\-[0-9]+$/
Using regex.powertoy.org
Regex (PHP/Perl-like syntax:
m/^[\d]+\s*-\s*[\d]+$/m
Test:
70-60
50-40
100 -90
matches all three test strings.
Note the trailing m
makes this a multi-line match (leading m
makes this a matching regex not a substituting regex). If you put all your test data in the test area and don't use a multi-line match it won't match (well it might match the first one...) because it's trying to match the whole input (^ to $) but that regex will only match each line. Change the test data to just one (70-60
) and it works without the m
.
^[\d]+-[\d]+$
Aswell as some of the other answers works with your test data IF, you check the ^$ matches line breaks.
/^[\d]+-[\d]+$/m
Would then be the expression you should use
worked it out finally...!!!
/[\d]+:?[\d]*/
this would check for each of the following
100
100:90
90:70
thanks everybody for u'r valuable inputs...
精彩评论