SpikETidE
SpikETidE

Reputation: 6961

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:

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 me? Thanks a lot in advance.

Upvotes: 0

Views: 1743

Answers (6)

Nestor
Nestor

Reputation: 13990

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

Upvotes: 1

cgr
cgr

Reputation: 1121

the $ needs to be within the regex

/^[0-9]+-[0-9]+$/

Upvotes: 3

SpikETidE
SpikETidE

Reputation: 6961

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

Upvotes: 0

Kristoffer Sall-Storgaard
Kristoffer Sall-Storgaard

Reputation: 10636

^[\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

Upvotes: 0

beggs
beggs

Reputation: 4195

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.

Upvotes: 0

Matt
Matt

Reputation: 509

You're a bit off on the regular expression syntax. What you want is:

/^[0-9]+\-[0-9]+$/

Upvotes: 0

Related Questions