简体   繁体   中英

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:

  • 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? Ie I don't want the whole string to be matched .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM