Home > Mobile >  Regex: string match with flexible number matching
Regex: string match with flexible number matching

Time:02-17

I need to use RegEx for matching and was hoping somebody with much more experience than me could help.

The 'Stable tag:' string doesn't change however the following numbers change. I want to match all versions below 3.0 no matter how many decimal points they have.

Stable tag: 4.1.5.3
Stable tag: 11.0.5.3
Stable tag: 23.1.5.3
Stable tag: 13.0.1
Stable tag: 13.0
Stable tag: 2.0.1
Stable tag: 3.0.21.4.2
Stable tag: 3.0
Stable tag: 3.0.111.32
Stable tag: 1.0.1.3

The closest RegEx I have gotten which is somewhat reliable is Stable tag\: [3]\.[0].([1]|[2]|[3]|[4]|[5]|[6]|[7])|[3]\.[0]$ however this only matches versions 3.0.

RegEx101 link here: https://regex101.com/r/ehOL2n/1

Hoping someone can help, thank you!

CodePudding user response:

First section is \d to capture major version. The rest of the version is just . and digits. So we can specify that as (?:\.\d ) and it can be zero or more *.

/Stable tag\: (\d (?:\.\d )*)$/

Working example: https://regex101.com/r/fxYE2M/1

CodePudding user response:

"I want to match all versions below 3.0 no matter how many decimal points they have."

Then you'll need to match not only 3 which is [3] but 1, 2, and 3 which is [123] or [1-3]. Anything between brackets (called a class) is a single litreral entity:

[1-3.*f] // 1, or 2, or 3, or ., or *, or f

Unless there's a quantifier proceeding it:

[12]* // 1, and/or 2, or nothing to an unlimited amount 

The full regex:

 /Stable tag\: [1-3][.][01][.]*[0-9.]*/g

const sTags = `
Stable tag: 4.1.5.3
Stable tag: 11.0.5.3
Stable tag: 23.1.5.3
Stable tag: 13.0.1
Stable tag: 13.0
Stable tag: 2.0.1
Stable tag: 3.0.21.4.2
Stable tag: 3.0
Stable tag: 3.0.111.32
Stable tag: 1.0.1.3`;

const rgx = new RegExp(/Stable tag\: [1-3][.][01][.]*[0-9.]*/, 'g');

const matches = [...sTags.matchAll(rgx)].map(m => `${m[0]}`);

console.log(matches);

  • Related