1

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.

3
  • 3
    What do you mean by "more precise"? Commented May 2, 2019 at 16:08
  • 1
    What is AppConstants.ROLLING_DEP_DATE_REGEX? Why not use the regexp to match what you describe? (e.g. /(-?\d+)-(-?\d+)/g) Commented May 2, 2019 at 16:09
  • 1
    Based on your comments, I updated the question, thanks! Commented May 2, 2019 at 17:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@user1485864 Did this helped you?
From your answer I understand that my question does not make sense. Indeed, I have to match the whole input string, as I need be certain that the two patterns (-?\d+) are separated by a -. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.