romainberger
romainberger

Reputation: 4558

Need some help to improve a regex

I lack experience with regex and I need some help. I need to extract a git tag. The input string is like this:

6dde3d91f23bff5ab81e91838f19f306b33fe7a8refs/tags/3.4.2

// there is a new line at the end of the string

The part of the string I need is 3.4.2. Here is my code:

var pattern = /.*([0-9]{1}\.{1}[0-9]{1}\.{1}[0-9]{1}).*/ig;
var match = pattern.exec(string);
// match[1] gets what I need

It works, but this regex is ridiculously long, there must be a way to make it shorter. Can somebody help me?

Thanks

Upvotes: 1

Views: 80

Answers (5)

softsdev
softsdev

Reputation: 1509

This is Shortest one >>

[0-9.]+$

Upvotes: 0

Saulo Silva
Saulo Silva

Reputation: 1287

You can replace [0-9]{1} with \d as follows:

/\d\.\d\.\d$/

The $ matches the end of the line.

Edit: updated based on Rob-W's feedback

Upvotes: 3

yodog
yodog

Reputation: 6232

i got your result with \d\..*

can't get any shorter than this.

test it here

Upvotes: 0

Jeff Ferland
Jeff Ferland

Reputation: 18282

The {1} is implicit in every statement. Taking those out will shorten your expression.

j08691's answer is the right thing, though: just string split it.

Upvotes: 0

j08691
j08691

Reputation: 207891

No regex is needed, just split the string.

var tag ="6dde3d91f23bff5ab81e91838f19f306b33fe7a8refs/tags/3.4.2";​​​​​
console.log(tag.split('/')[2]);​ // results in 3.4.2

Upvotes: 1

Related Questions