2

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?

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.