0

I have string "foo_FOO1" and "foo1_FOO1". I want to replace only the part "foo" with "x0" and the word "foo1" is not included. So the result of "foo_FOO1" has to be "x0_FOO1" and "foo1_FOO1" remains the same. Could you give me the solution in Java, please? I tried to use str.replaceAll("foo", "x0") but all string that contains "foo" will be replaced with "x0".

dedelduel
  • 53
  • 1
  • 1
  • 4

1 Answers1

0

Sketchy, but try to replace the _ too. Since foo1_ does not match foo_, Java will not replace it.

final String test = "foo_FOO1 foo1_FOO1";

final String result = test.replaceAll("foo_", "x0_");
System.out.println(result);

Result:

x0_FOO1 foo1_FOO1

Tests:

private String replaceFoo(final String value) {
    return value.replaceAll("foo_", "x0_");
}

@Test
public void testMultipleLines() {
    Assert.assertEquals("x0_FOO1 foo1_FOO1", replaceFoo("foo_FOO1 foo1_FOO1"));
    Assert.assertEquals("x0_FOO1\n\nfoo1_FOO1", replaceFoo("foo_FOO1\n\nfoo1_FOO1"));
}

@Test
public void testSingleLine() {
    Assert.assertEquals("x0_FOO1", replaceFoo("foo_FOO1"));
    Assert.assertEquals("foo1_FOO1", replaceFoo("foo1_FOO1"));
}

If the given String may not have a _, have a look at this: https://stackoverflow.com/a/16398813/15257712

Manuel
  • 188
  • 1
  • 12