Regex to select all character between underscores

Abhishek :

I am trying to write a regular expression to select all characters between underscores. I end up with _([^_]+)_ but it does not match all the groups,

String : abc_bca_vag_hag_bag output : bca vag hag

can someone help with this?

Sweeper :

Your regex will match the underscores, and things that are matched once will not be matched again. So after matching _bca_, it does not see that the last underscore in _bca_ is actually the same underscore that is before vag. It thinks that vag is not preceded by an underscore because it has already matched the underscore preceding it in the previous match.

You need to use lookaheads and lookbehinds:

(?<=_)[^_]+(?=_)

These will not match the underscore. They will only "look" and see whether there is an underscore.

Demo

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113415&siteId=1