How To Replace All Occurrences Of A String Inside Tags <> Using Regex In Java
I have a string inside tags. Eg: "<abc~a>I am src scr customer<abc~b>"
I want to replace "src" with "abc". I used following regex to replace:- replacAll("(<abc~a>.?)src(.?<abc~b>)"),"$1"+"abc"+"$2"); But it is replacing only first occurrence of string i.e. output is "<abc~a>I am abc src customer<abc~b>"
I want output as "<abc~a>I am abc abc customer<abc~b>".
I don't want to use matcher pattern. Is there any solution using replaceAll() ? Please help.
Answer
We can try using a formal regex pattern matcher here. Match on the pattern <abc~a>(.*?)<abc~a>
, and for each match append the tag with src
replaced by abc
. Here is a sample code:
String input = "Here is a src <abc~a>I am an src customer<abc~b> also another src here.";
Pattern p = Pattern.compile("<abc~a>(.*?)<abc~b>");
Matcher m = p.matcher(input);
StringBuffer buffer = new StringBuffer();
while(m.find()) {
String replace = "<abc~a>" + m.group(1).replaceAll("\\bsrc\\b", "abc") + "<abc~a>";
m.appendReplacement(buffer, replace);
}
m.appendTail(buffer);
System.out.println(buffer.toString());
This prints:
Here is a src <abc~a>I am an abc customer<abc~b> also another src here.
Note that in many other languages we could have used a regex callback function. But core Java does not support this functionality, so we have to iterate over the entire input.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM