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"
.
Asked
Active
Viewed 48 times
0

dedelduel
- 53
- 1
- 1
- 4
1 Answers
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
-
thank you, but the string "foo_FOO1" and "foo1_FOO1" is not in one line. it's just an example with 2 cases :-) – dedelduel Jun 21 '21 at 07:50
-
I'm not sure what you want. Inline, single and multi-line works fine for me. Am i overlooking any test cases? (I attached mine above) – Manuel Jun 21 '21 at 08:10
-
1I'm sorry, I was just not focused on your solution :D yup, it works. thank you!!! – dedelduel Jun 21 '21 at 08:21
-
I'm glad that it works! Will you mark the question as resolved? – Manuel Jun 21 '21 at 08:59