2

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("\\,"));
    }
}
3
  • 1
    Would you mind formatting your post to improve its display quality? You seem to be a long time member of this site and probably know what a good quality post should look like. Commented Mar 28, 2019 at 11:16
  • 1
    Use .replaceAll("\\btest[^,]*", ""). However, if you replace + with +?, it would also work. Commented Mar 28, 2019 at 11:19
  • If a string contains "test" followed by nothing but a comma (so "test,") should "test" be removed as well? Commented Mar 28, 2019 at 11:35

1 Answer 1

2

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[^,]+", "");
}
Sign up to request clarification or add additional context in comments.

Comments

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.