简体   繁体   中英

Fetch datas between two tags

I have got the following string

   String s =  "{s}lorem ipsum{/s}
    explanation for lorem ipsum
    {s}dolar sit amet{/s}
    explanation for dolar sit amet";

I would like to parse it in two ways. I want to fetch the texts thats within {s}{/s} tag and texts thats not enclosed by {s}{/s}.

I tried the following code.

 String firstRemovePattern        = "\\{"  + "\\}";
            String replacedWithFirstPattern  = s.replaceAll(firstRemovePattern, "");

but the above code doesnt fetch the expected strings. How can i be able to sort this out?

You can use this regex to get both parts separately:

\{(\w+)\}(.*?){/\1}((?:(?!\{\w+\}).)*)
  • Group #2 will give you text in between the tags.
  • Group #3 will give you text outside the tags.

RegEx Demo


If your input doesn't start with a tag then use:

((?:(?!\{\w+\}).)*)\{(\w+)\}(.*?){/\2}((?:(?!\{\w+\}).)*)
  • Group #1 + Group #4 will give you text outside the tags.
  • Group #3 will give you text inside the tags.

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