user1191027
user1191027

Reputation:

Replacing Pattern Matches in a String

String output = "";
pattern = Pattern.compile(">Part\s.");
matcher = pattern.matcher(docToProcess);
while (matcher.find()) {
      match = matcher.group();
}

I'm trying to use the above code to find the pattern >Part\s. inside docToProcess (Which is a string of a large xml document) and then what I want to do is replace the content that matches the pattern with <ref></ref>

Any ideas how I can make the output variable equal to docToProcess except with the replacements as indicated above?

EDIT: I need to use the matcher somehow when replacing. I can't just use replaceAll()

Upvotes: 0

Views: 230

Answers (4)

Rohit Jain
Rohit Jain

Reputation: 213223

You can use String#replaceAll method. It takes a Regex as first parameter: -

String output = docToProcess.replaceAll(">Part\\s\\.", "<ref></ref>");

Note that, dot (.) is a special meta-character in regex, which matches everything, and not just a dot(.). So, you need to escape it, unless you really wanted to match any character after >Part\\s. And you need to add 2 backslashes to escape in Java.


If you want to use Matcher class, the you can use Matcher.appendReplacement method: -

 String docToProcess = "XYZ>Part .asdf";
 Pattern p = Pattern.compile(">Part\\s\\.");
 Matcher m = p.matcher(docToProcess);
 StringBuffer sb = new StringBuffer();
 while (m.find()) {
     m.appendReplacement(sb, "<ref></ref>");
 }
 m.appendTail(sb);
 System.out.println(sb.toString());

OUTPUT : -

"XYZ<ref></ref>asdf"

Upvotes: 2

Marko Topolnik
Marko Topolnik

Reputation: 200148

This is what you need:

String docToProcess = "... your xml here ...";
Pattern pattern = Pattern.compile(">Part\\s.");
Matcher matcher = pattern.matcher(docToProcess);
StringBuffer output = new StringBuffer();
while (matcher.find()) matcher.appendReplacement(output, "<ref></ref>");
matcher.appendTail(output);

Unfortunately, you can't use the StringBuilder due to historical constraints on the Java API.

Upvotes: 2

jlordo
jlordo

Reputation: 37813

String output = docToProcess.replaceAll(">Part\\s\\.", "<ref></ref>");

Upvotes: 0

Alex
Alex

Reputation: 25613

docToProcess.replaceAll(">Part\\s[.]", "<ref></ref>");

Upvotes: 0

Related Questions