Skip to content
Advertisement

combine regex to match subgroups in different order

I have a string with may have one of the 2 below structure

(w+){1}([!][a-zA-Z0-9>,]+)*([#]d+)?

(w+){1}([#]d+)?([!][a-zA-Z0-9>,]+)*

some examples would be

"Abc1!deF2>Ghi3,4jlmNO!pQr5st#1400"
"Abc1#1400!deF2>Ghi3,4jlmNO!pQr5st"

The goal is to match as below

["Abc1", "!deF2>Ghi3,4jlmNO", "!pQr5st", "#1400"]
["Abc1", "#1400", "!deF2>Ghi3,4jlmNO", "!pQr5st"]

I can manage to get the result with 3 regex, but not with 1

const a = str.match(/w+/)
const b = str.match(/([!][a-zA-Z0-9>,]+)/g)
const c = str.match(/[#]d+/)

How can I get the expected result with a single regex ?

Advertisement

Answer

Maybe use | to separate possible matches:

const regExp = /w+|![a-zA-Z0-9>,]+|#d+/g;

console.log("Abc1!deF2>Ghi3,4jlmNO!pQr5st#1400".match(regExp));
console.log("Abc1#1400!deF2>Ghi3,4jlmNO!pQr5st".match(regExp));

Also note that (w+){1} is equivalent to w+, and [!] and [#] are the same as ! and # respectively.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement