Ali
Ali

Reputation: 8100

Java RegEx: Replace part of source string

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

Upvotes: 3

Views: 13357

Answers (2)

aioobe
aioobe

Reputation: 421340

// 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"

Upvotes: 9

Thomas
Thomas

Reputation: 88757

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

Upvotes: 2

Related Questions