Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java RegEx: Replace part of source string

Tags:

java

regex

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

like image 443
Ali Avatar asked Mar 24 '26 11:03

Ali


2 Answers

// 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"
like image 198
aioobe Avatar answered Mar 27 '26 01:03

aioobe


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
like image 41
Thomas Avatar answered Mar 27 '26 00:03

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!