1

I am trying to get number i.e. 1.0.3 from string . I only want numbers that are formatted with two dots and have ver# before them. Is my regex implementation correct. It is work but will it fail in any condition?

var str = "https://example.x.y.com/z/ver#1.5.0"; 
var res = str.match(/ver#.\.(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)/g);
return res;

https://jsfiddle.net/tthfkzjt/

5
  • Suggest you take a look here - regex101.com/r/vJ4qU1/1 Commented Mar 11, 2016 at 14:26
  • 3
    I guess even a simpler regex like this #\d+\.\d+.\d+ will be suffice. Demo Commented Mar 11, 2016 at 14:26
  • As @noob posted - regex101.com/r/vJ4qU1/2. That one will not match ver#a.0.5 whereas your original one does match ver#a.0.5. You are probably better off using theirs. Commented Mar 11, 2016 at 14:28
  • @JosephGarrone. it's Commented Mar 11, 2016 at 14:30
  • Thanks everyone for sharing the information Commented Mar 11, 2016 at 22:30

1 Answer 1

1

I am trying to get number i.e. 1.0.3 from string . I only want numbers that are formatted with two dots and have ver# before them

This could be done by simple regex: /ver#(\d+\.\d+\.\d+)/

Capture the first group using \1 or $1.

Regex101 Demo

JS Fiddle

var str = "https://example.x.y.com/z/ver#1.5.0"; 
var res = str.match(/ver#(\d+\.\d+\.\d+)/);
document.getElementById("res").innerHTML = res ? res[1] : "";
<div id="res"/>

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

4 Comments

Second dot should be escaped so it matches dot literally instead of matching any character. /ver#(\d+\.\d+\.\d+)/. @noob can you edit it. Thanks!
@Wiktor Stribiżew: How did we missed this obvious thing ? Was there any reason not to escape second dot ?
If there is more than one issue in a solution, the possibility of overlooking one of them is very high. In this case, I was not focused on the expression itself, just on the JS code: I just blindly copied the pattern to jsfiddle.net from regex101.com and pasted here.
@bitecoder: Thanks for pointing out the mistake. Appreciate it !

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.