I need to convert a string like
"string"
to
"*s*t*r*i*n*g*"
What’s the regex pattern? Language is Java.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You want to match an empty string, and replace with
"*". So, something like this works:Or better yet, since the empty string can be matched literally without regex, you can just do:
Why this works
It’s because any instance of a string
startsWith(""), andendsWith(""), andcontains("").Between any two characters in any string, there’s an empty string. In fact, there are infinite number of empty strings at these locations.(And yes, this is true for the empty string itself. That is an “empty” string
containsitself!).The regex engine and
String.replaceautomatically advances the index when looking for the next match in these kinds of cases to prevent an infinite loop.A “real” regex solution
There’s no need for this, but it’s shown here for educational purpose: something like this also works:
This works by matching “any” character with
., and replacing it with*and that character, by backreferencing to group 0.To add the asterisk for the last character, we allow
.to be matched optionally with.?. This works because?is greedy and will always take a character if possible, i.e. anywhere but the last character.If the string may contain newline characters, then use
Pattern.DOTALL/(?s)mode.References