Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 : matching expression using regex

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?

like image 732
Anudocs Avatar asked Sep 01 '26 23:09

Anudocs


2 Answers

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
  • $: End
like image 96
anubhava Avatar answered Sep 03 '26 12:09

anubhava


The 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 string

Regex demo

like image 38
The fourth bird Avatar answered Sep 03 '26 14:09

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!