1

How would I modify the following javascript regexp so that it matches all of the proceeding patterns?

/(\d\d).+?(\d\d)/

2 of 5
2.5 of 5.6
2.3 of 10
100.4 of 1000
1000.4 of 10000.3

2 Answers 2

3

Try this:

/(\d+(?:\.\d+)?).+?(\d+(?:\.\d+)?)/

This will match one or more decimals followed by an optional decimal point and one or more decimals, captured in group 1, followed by one or more of any character, non-greedily, followed by one or more decimals followed by an optional decimal point and one or more decimals, captured in group 2.

Demonstration

Also, if you want to prevent any other characters before or after the matched string, you may need to add a start (^) and end ($) anchor:

/^(\d+(?:\.\d+)?).+?(\d+(?:\.\d+)?)$/
Sign up to request clarification or add additional context in comments.

4 Comments

What's the ?: purpose?
I believe that is a non-capturing group?
@cvsguimaraes It creates a non-capturing group. They may not be needed, but I'm using that to ensure that OP's groups still return what seems to be expected (group 1 contains the first number, group 2 the second).
@cvsguimaraes Thanks bud, I will accept the appropriate answer once I'm sure it solves the problem at hand. But thanks for the beginner's lesson.
1
/\d+(\.\d+)? of \d+(\.\d+)?/
  1. \d+ at least one digit
  2. (\.\d+)? with optional decimals
  3. of the string between these two numbers
  4. \d+ followed by at least one digit
  5. \d+ with optional decimals

Comments

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.