2

I have series of numbers (versioning) like this:

1.6.8
1.9.7 (also with two digits in the middle)

How should I do to target only the middle numbers, the ones between dot and dot?

I tried something like that this:

\.\d+(?=\.)

and it is targeting the middle number, but also the first dot.

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
pitygacio
  • 41
  • 6
  • 1
    Then try `(?<=\.)\d+(?=\.)`. Or use a capturing group, `\.(\d+)\.` – Wiktor Stribiżew Jun 12 '19 at 09:54
  • Wiktor's second suggestion is much more readable than the first one, and should work fine. A simpler solution might be to use split(".") – MikeB Jun 12 '19 at 09:58
  • The first approach it's not working for me and I already tried the second one, but it's also selecting the dots and not just the numbers – pitygacio Jun 12 '19 at 10:03
  • Well, I posted my comment when the question had no `javascript` tag. Certainly, the first regex won't work in the majority of current JS environments. The second one does exactly what you need once you access Group 1 value. And since you tried it before all you need to know is how to get to the groups which is a long solved issue. – Wiktor Stribiżew Jun 12 '19 at 10:29

2 Answers2

2

Something like this?

var myRegexp = /\d+\.(\d+)\.\d+/;

var match = myRegexp.exec('1.33.4');
console.log(match[1]); //33
var match = myRegexp.exec('441.54.12345647');
console.log(match[1]); //54
match = myRegexp.exec('13.2222.33');
console.log(match[1]); //2222

match = myRegexp.exec('version 1.2.3');
console.log(match[1]); //2

function getMiddle(inputversion) {
    var myRegexp = /\d+\.(\d+)\.\d+/;
    var match = myRegexp.exec(inputversion);
    if(match != null) {
        if(match.length > 0) {
            return match[1];
        }
    }
    return null;
}

console.log('should be 34:', getMiddle('my app version: 1.34.55'));
console.log('should be null:', getMiddle('my app needs no versions.it.is.awesome'));

The group selector () matches the most middle digits.
The + makes sure also larger numbers than 9 can get captured.

https://regex101.com/r/wFgpRI/3

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
  • Hmm, that is targeting all the numbers and not just the ones between the dots. That's why I tried \.\d+\. but that it's also returning the dots and not just the numbers – pitygacio Jun 12 '19 at 10:04
  • @pitygacio added example on how to extract the group. – Tschallacka Jun 12 '19 at 10:07
1

I don't see a need for using regex here. You could use split:

var versions = '1.6.8 1.9.7'

console.log(versions.split(' ').map(el => el.split('.')[1]))

If you don't want to use that method, you could use regex anyway, as pointed out by wiktor:

var versions = '1.6.8 1.9.7'
console.log(versions.match(/(?<=\.)\d+(?=\.)/g))
Kobe
  • 6,226
  • 1
  • 14
  • 35