简体   繁体   中英

Java regular expression to match everything between same specific character sequences

Let's take string "Something foo part1 foo part2 foo part3" as an example.

I want to find all parts starting with "foo" continuing till another "foo" or end of string and replace (wrap inner part into HTML markup) afterwards. So the result should be "Something <bar> part1 </bar><bar> part2 </bar><bar> part3</bar>"

I've started with: "foo(.*?)(foo|$)" and replacing it with "<bar>$1</bar>" . Replacing seems to be all right but I need help with regex itself.

I have tried many variations with negative lookbehind and others so far without success. Thanks for any suggestions.

Just change your second group into a lookahead

foo(.*?)(?=foo|$)

See it on Regexr

The problem is you are matching the "foo" that you want to use as next start point. You can avoid this by using the lookahead assertion . This way the following "foo" is not matched and therefor used as start of the next match.

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