简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM