Home > database >  Node regex pattern to extract version and filename
Node regex pattern to extract version and filename

Time:04-30

I need help with a regex expression to extract the name and the version from a filename string eg:

"ABC V1.2.3 4.exe"
"file name with spacesV1.2.3 4.exe"
"etc...V1.2.3 4.exe"

the version part is always in the format VX.Y.Z B but the name (anything before 'V' can be anything)

I was able to extract the version number with this regex pattern:

/V(\d )(\.\d )(\.\d )(\ \d )?/g (build number is optional)

For example:

let file = "HelloWorld V4.5.6 7.exe"; 
console.log(file.match(/V(\d )(\.\d )(\.\d )(\ \d )?/g));

output: [ 'V4.5.6 7' ]

So far so good. but I also want the part from the start of the string till the matched version number.

I want the output to be:

['whatever is before the matched version number', 'V4.5.6 7']

I'm not so good with regex and I've spend 4 hours trying.

CodePudding user response:

Use .* to match everything before the version number. Put capture groups around the prefix and the version parts of the regexp.

Don't use the g flag. That makes it return all the complete matches, rather than an array of capture groups. Since there can only be one match, there's no need for the global flag.

let file = "HelloWorld V4.5.6 7.exe"; 
console.log(file.match(/^(.*)V(\d \.\d \.\d (?:\ \d )?)/));

  • Related