I have a string with may have one of the 2 below structure
JavaScript
x
4
1
(w+){1}([!][a-zA-Z0-9>,]+)*([#]d+)?
2
3
(w+){1}([#]d+)?([!][a-zA-Z0-9>,]+)*
4
some examples would be
JavaScript
1
3
1
"Abc1!deF2>Ghi3,4jlmNO!pQr5st#1400"
2
"Abc1#1400!deF2>Ghi3,4jlmNO!pQr5st"
3
The goal is to match as below
JavaScript
1
3
1
["Abc1", "!deF2>Ghi3,4jlmNO", "!pQr5st", "#1400"]
2
["Abc1", "#1400", "!deF2>Ghi3,4jlmNO", "!pQr5st"]
3
I can manage to get the result with 3 regex, but not with 1
JavaScript
1
4
1
const a = str.match(/w+/)
2
const b = str.match(/([!][a-zA-Z0-9>,]+)/g)
3
const c = str.match(/[#]d+/)
4
How can I get the expected result with a single regex ?
Advertisement
Answer
Maybe use |
to separate possible matches:
JavaScript
1
4
1
const regExp = /w+|![a-zA-Z0-9>,]+|#d+/g;
2
3
console.log("Abc1!deF2>Ghi3,4jlmNO!pQr5st#1400".match(regExp));
4
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.