3

If the source string contains the pattern, then replace it with something or remove it. One way to do it is to do something like this

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(sourceString);
while(m.find()){
  String subStr = m.group().replaceAll('something',""); // remove the pattern sequence
  String strPart1 = sourceString.subString(0,m.start());
  String strPart2 = sourceString.subString(m.start()+1);
  String resultingStr = strPart1+subStr+strPart2;
  p.matcher(...);
}

But I want something like this

Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(sourceString);
    while(m.find()){
      m.group.replaceAll(...);// change the group and it is source string is automatically updated    
}

Is this possible?

Thanks

2
  • 'something' that wouldn't compile, it's not a character but a string. Commented Oct 14, 2011 at 7:42
  • Do you mean you want to replace a pattern in your string with something else? Did you try String#replaceAll("pattern","replacement")? Commented Oct 14, 2011 at 7:43

2 Answers 2

9

// change the group and it is source string is automatically updated

There is no way what so ever to change any string in Java, so what you're asking for is impossible.

To remove or replace a pattern with a string can be achieved with a call like

someString = someString.replaceAll(toReplace, replacement);

To transform the matched substring, as seems to be indicated by your line

m.group().replaceAll("something","");

the best solution is probably to use

  • A StringBuffer for the result
  • Matcher.appendReplacement and Matcher.appendTail.

Example:

String regex = "ipsum";
String sourceString = "lorem ipsum dolor sit";

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(sourceString);
StringBuffer sb = new StringBuffer();

while (m.find()) {
    // For example: transform match to upper case
    String replacement = m.group().toUpperCase();
    m.appendReplacement(sb, replacement);
}

m.appendTail(sb);

sourceString = sb.toString();

System.out.println(sourceString); // "lorem IPSUM dolor sit"
Sign up to request clarification or add additional context in comments.

Comments

2

Assuming you want to replace all occurences of a certain pattern, try this:

String source = "aabbaabbaabbaa";
String result = source.replaceAll("aa", "xx");  //results in xxbbxxbbxxbbxx

Removing the pattern would then be:

String result = source.replaceAll("aa", ""); //results in bbbbbb

2 Comments

This is a good approach unless you need to transform the matched substring.
@aioobe Exactly, I was struggling to explain that. That exactly what I want to do. To transform the matched substring and somehow put it back in the original string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.