I am looking for regex which can help me replace strings like
source=abc/task=cde/env=it --> source='abc'/task='cde'/env='it'
Tried code like this : "source=abc/task=cde/env=it".replaceAll("=(.*?)/","'$1'")
but getting final string = source'abc'task'cde'env=it
CodePudding user response:
Try
String input = "source=abc/task=cde/env=it".replaceAll("=(.*?)(/|$)","='$1'/");
The problems I found are that you are not replacing the =
and also the /
is not there for the end of String, that also needs to be replaced when found.
output
source='abc'/task='cde'/env='it'/
If you don't want the last '/', that is trivial to remove isn't it.
CodePudding user response:
Using lookahead and look behind:
(?<==)([^/]*)((?=/)|$)
It also matches the end of the String.
@Test
public void test_quote_items() {
String regex = "(?<==)([^/]*)((?=/)|$)";
String actual = "source=abc/task=cde/env=it".replaceAll(regex,"'$1'");
String expected = "source='abc'/task='cde'/env='it'";
assertEquals(expected, actual);
}