Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regex to detect underscore between letters

Tags:

python

regex

How do I make a regex in python that returns a string with all underscores between lowercase letters? For example, it should detect and return: 'aa_bb_cc' , 'swd_qq' , 'hello_there_friend'

But it should not return these: 'aA_bb' , 'aa_' , '_ddQ' , 'aa_baa_2cs'

My code is ([a-z]+_[a-z]+)+ , but it returns only one underscore. It should return all underscores seperated by lowercase letters.

For example, when I pass the string "aab_cbbbc_vv", it returns only 'aab_cbbbc' instead of 'aab_cbbbc_vv'

Thank you

like image 861
cxs101 Avatar asked Nov 24 '25 21:11

cxs101


1 Answers

Your regex is almost correct. If you change it to:

^([a-z]+)(_[a-z]+)+$

It woks as you can check here.

^ - matches the beginning of the string

$ - the end of the string

You need these so that you are not getting partial matches when matching the strings you don't want to get matched.

like image 192
sophros Avatar answered Nov 26 '25 10:11

sophros



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!