Replace A Pattern In String Using Java

chetan :

I need to replace test word up to next comma in a string.
For example the string is "abc test xy, tmy test 1, vks , csb";
The output after replacement should be "abc , tmy, vks,csb".
Removed test followed by any character or number up to comma.

I tried the following code but did not work.

import java.sql.Timestamp;
import java.time.Instant;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class TESTREPLACE {

    public static void main(String[] args) {
        String str = "abc test   xy, tcs test  1, vks , csb ";

        String regex = " default.+\\,";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        System.out.println(matcher.replaceAll("\\,"));
    }
}
burm87 :

The requirements are not very clear in your example, do you also need to remove spaces after commas? Anyway this regex is matching the word test followed by any character except for the comma ,: (test[^,]+) using it in your replaceAll should do the trick.

@Test
public void test() {
    final String input = "abc test xy, tmy test 1, vks , csb";
    final String expected = "abc , tmy , vks , csb";
    final String got = replaceTestWordUpToComma(input);
    assertEquals(expected, got);
}

private String replaceTestWordUpToComma(String input) {
    return input.replaceAll("test[^,]+", "");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=150954&siteId=1