Salman A. Kagzi
Salman A. Kagzi

Reputation: 4053

Regular expression for String.replaceAll

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

Answers (2)

FailedDev
FailedDev

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

stevevls
stevevls

Reputation: 10843

it may be possible to do without capture groups, but this should work:

myString.replaceAll("\\*([^\\\\]|$)", "*.$1");

Upvotes: 1

Related Questions