简体   繁体   中英

RegEx to capture text between two delimiter characters including 'shared'

If I have the following text...

The quick :brown:fox: jumped over the lazy :dog:.

I would like a regular expression to capture all the words that are between 2 : characters. In the above example it should return :brown: , :fox: , :dog: .

So far, I have this (\\:{1}.\\w*\\s*\\:{1}) which returns :brown: and :dog: . I can't quite figure out how to share the : between the 2 matching groups so that it will also return ':fox:' .

Here is a simple pattern which can be made to work:

(?<=:)(\w+)(?=:)

This uses lookarounds to make sure that one or more word characters are surrounded before and after by colons. Check the demo below to see it working.

The match would be available as the first capture group. Actually, it should also be available as the entire match itself, because lookarounds do not consume anything.

Demo

I like the above lookaround approach because it is clean and simple (at least in my mind). If, for some reason, you don't want any lookarounds, then just use the following pattern:

:(\w+):

But note that now you explicitly have to access the first capture group to obtain the matching word without colons on either side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM