Reputation: 519
This is my regex: (-?\d+)-(-?\d+)
.
The purpose is to match strings that denote ranges, including negative ones. For example:
1-10
0-100
-1-10
, but also:-100--10
Then with my regex, I will capture the first number, the last, but also the whole string. In Angular:
let regExp : RegExp = RegExp('(-?\\d+)-(-?\\d+)', 'g');
let values: RegExpExecArray = regExp.exec('-100--10');
From the values
result, I can use positions values[1]
and values[2]
, as values[0]
is reserved for the whole string.
Obviously, the above works for me, but do you have any idea how to make my regex more precise? I.e. I don't want the whole string to be matched.
Upvotes: 1
Views: 185
Reputation: 2892
In your pattern (-?\\d+)
is repeating so you can use only this pattern to match in text
.
let pattern = RegExp('(-?\\d+)', 'g')
let text = '-100--10'
text.match(pattern) //output: ["-100", "-10"]
This way, you don't have to match entire string.
Upvotes: 1