Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node regex pattern to extract version and filename

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/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.

>Solution :

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+)?)/));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading