rss
twitter

Saturday, April 30, 2011

Replace all characters with in two tags using Regular expressions in Java

We can do the string functions like replace and find using simple regular expressions easily.Regular expression is easier to use with javascript replace function. Here are the regular expressions to replace the entire contents occur between two tags in Java. Here, for example the regular expression removes the content in <-! Tag -> and <-! End Tag ->. In java we need to use Pattern and Matcher classes.

private static final Pattern tag = Pattern.compile(
            "<!--\\s*Tag\\s*-->(.*?)<!--\\s*End Tag\\s*-->", Pattern.CASE_INSENSITIVE);
 
Matcher matcher = tag.matcher(aText);
         result = matcher.replaceAll("");

By changing the line to Pattern.DOTALL from Pattern.CASE_INSENSITIVE the regular expressions check the availability of tags in multi-line too. Pattern.DOTALL includes multi-line charater also in the search.

Bookmark and Share

6 comments:

knot May 1, 2011 at 10:30 PM  

Replace all characters with in two tags using Regular expressions in Java Good post

foxliquidation September 11, 2013 at 1:48 PM  

thanks I was looking for this!

Ron November 17, 2013 at 2:58 PM  
This comment has been removed by a blog administrator.
Ron November 17, 2013 at 3:03 PM  
This comment has been removed by a blog administrator.
Ron November 17, 2013 at 5:43 PM  
This comment has been removed by a blog administrator.
Ron February 14, 2014 at 12:50 PM  
This comment has been removed by a blog administrator.

Post a Comment

Tech World

Label Cloud

Must Buy

  © Blogger templates by Ourblogtemplates.com updated with zenplate.com tips

Back to TOP