Reputation: 111
I'm trying to write a regex pattern to match strings like:
+500-+600
The pattern should only accept +
when there is a number after, and should only accept -
(hyphen) between two numbers.
So far I could only get the pattern working for the +
which is:
/^\+?([0-9]+)$/
But I couldn't figure out how to add the -
to the pattern.
Any thoughts?
Thank you
Upvotes: 0
Views: 247
Reputation: 14564
+
is a special character in regex, so you must escape it with \
if you want to interpret it as a string literal.
/^\+\d+-\+\d+$/
This will match all strings where you have two numbers separated by a hyphen (as per your example +500-+600
).
If the second number is optional but there can only be two numbers, use this:
/^\+\d+(-\+\d+)?$/
This matches:
+500
+500-+600
If there can be any number of additional hyphen-separated numbers, use this:
/^\+\d+(-\+\d+)*$/
This matches:
+500
+500-+600
+500-+600-+700
Upvotes: 1