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.
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.
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.
6 comments:
Replace all characters with in two tags using Regular expressions in Java Good post
thanks I was looking for this!
Post a Comment