Reputation: 4053
I need a regular expression that can be used with replaceAll
method of String class to replace all instance of *
with .*
except for one that has trailing \
i.e. conversion would be
[any character]*[any character] => [any character].*[any character]
* => .*
\* => \* (i.e. no conversion.)
Can someone please help me?
Upvotes: 2
Views: 340
Reputation: 26930
Use lookbehind.
String resultString = subjectString.replaceAll("(?<!\\\\)\\*", ".*");
Explanation :
"(?<!" + // Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind)
"\\\\" + // Match the character “\” literally
")" +
"\\*" // Match the character “*” literally
Upvotes: 4
Reputation: 10843
it may be possible to do without capture groups, but this should work:
myString.replaceAll("\\*([^\\\\]|$)", "*.$1");
Upvotes: 1