user1485864
user1485864

Reputation: 519

Javascript regex to match part of the string but not the whole string

This is my regex: (-?\d+)-(-?\d+).

The purpose is to match strings that denote ranges, including negative ones. For example:

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

Answers (1)

mukesh210
mukesh210

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

Related Questions