Using split with regex isn't replaced right?

I am trying to parse lines of text to extract 4 version numbers:

v.1.7.600.0 - latest | 9.2.6200.0 to 9.2.9999

I am looking for the ability to parse a string like this:

['v.1.7.600.0', 'latest', '9.2.6200.0', '9.2.9999']

At the moment, I have something like this:

var line = "v.1.7.600.0 - latest | 9.2.6200.0 to 9.2.9999"
var result = line.split(/ (\||-|to) /g)
console.log(result)
Run codeHide result

I'm not so good at regex, but it matches, so I'm not sure why it includes them in the result.

+4
source share
1 answer

You are almost there, just use a non-capture group:

var line = "v.1.7.600.0 - latest | 9.2.6200.0 to 9.2.9999";
var result = line.split(/\s+(?:\||-|to)\s+/);
console.log(result);
Run codeHide result

You need a group that does not capture capture because it split()will extract the captured values ​​into the resulting array.

, \s+, .

, /g split(), .

char /\s+(?:[|-]|to)\s+/ regex.

+6

Source: https://habr.com/ru/post/1659715/


All Articles