I have below strings :
asc_epsWarn_mu8 # I want asc and epsWarn
asc_ger_phiK_mi16 # I want asc and ger_Phik
ARSrt_FAC_RED5_DSR_AU16 # I want ARSrt and FAC_RED5_DSR
Basically I want the the characters before the first _ in one group and all characters between the first and last underscore _ in second group.
I am new to regex. Is it possible to write a single regex expression for all above mentioned strings. The Best I could come up with is
(\w+)_(\w+)_(\w+)
But it does not work. What could be the right regex?
You may use this regex with 2 capture groups:
^([^_]+)_(.+)_[^_]*$
RegEx Demo
RegEx Details:
^: Start([^_]+): Capture group #1 to match 1+ non-underscore characters_: Match a -(.+): Capture group #2 to match 1+ of any character till next match_: Match a -[^_]*: Match 0 or more non-underscore characters$: EndThe wordcharacter \w Also matches an underscore.
If you want to match word characters without the underscore you can use a negated character class and match a non-whitespace char withtout the underscore [^\W_]
You might use 2 capturing groups with a repeating pattern for the second group:
^([^\W_]+)_((?:[^\W_]+_)*)[^\W_]+$
^ Start of string([^\W_]+)_ Match 1+ times a word char except an underscore in group 1, match underscore( Capturing group 2
(?:[^\W_]+_)* Repeat 0+ times matching word char except an underscore, then an underscore) Close group 2[^\W_]+ Match 1+ times a word char except an underscore$ End of stringRegex demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With