Reputation: 1395
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("\\,"));
}
}
Upvotes: 2
Views: 163
Reputation: 848
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[^,]+", "");
}
Upvotes: 2