0

I have strings like:

1.2.3
1.4.0.136
V312
V10
2.2.2
r1elease2.0.0
Vr 1.5.1

I want to get regex that should extract versions (without string) out of these strings and arrange in sorter order. Any two strings can be passed at a time to compare.

1.2.3 should become 1.2.3 (no change)
1.4.0.136 should become 1.4.0.136 (no change)
V312 should become 312 
V10 should become 10
2.2.2 should become 2.2.2 (no change)
r1elease2.0.0 should become 2.0.0
Vr 1.5.1 should become 1.5.1

I tried /[^0-9\.]+/g but it didn't worked in case r1elease2.0.0 as this string became 12.0.0 which is incorrect.

3
  • This should work for you /\d+(\.?\d+)+/g Commented Apr 25, 2018 at 16:51
  • Is there any case where the string part comes later like 1.0.0-SNAPSHOT ? Commented Apr 25, 2018 at 16:55
  • What language or tool? Commented Apr 25, 2018 at 17:13

3 Answers 3

2

For you example data, you could use:

\d+(?:\.\d+)*\b

This will match one or more digits followed by a zero or more times repeated pattern of a dot and one or more digits. It ends with a word boundary \b so the 1 in r1elease2.0.0 does not match.

Explanation

  • \d+ One or more digits
  • (?: Non capturing group
    • \.\d+ Match a dot and one or more digits
  • )* Close non capturing group and repeat zero or more times
  • \b Word boundary
Sign up to request clarification or add additional context in comments.

Comments

0

Try:

(?<=^|[\w\s])\d+(?:\.?\d+)*$

Demo

Comments

0

You can do:

(\w\s?)*?(\d+(?:\.\d+)*\b)

and perform the replacement with captured group 2. The part with \d+(?:\.\d+)*\b was explained by The fourth birth. The part (\w\s?)*? gets discarded in the replacement. Output:

1.2.3
1.4.0.136
312
10
2.2.2
2.0
1.5.1

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.