Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert "string" to "*s*t*r*i*n*g*"

I need to convert a string like

"string"

to

"*s*t*r*i*n*g*"

What's the regex pattern? Language is Java.

like image 213
DeepL Avatar asked Nov 27 '22 08:11

DeepL


1 Answers

You want to match an empty string, and replace with "*". So, something like this works:

System.out.println("string".replaceAll("", "*"));
// "*s*t*r*i*n*g*"

Or better yet, since the empty string can be matched literally without regex, you can just do:

System.out.println("string".replace("", "*"));
// "*s*t*r*i*n*g*"

Why this works

It's because any instance of a string startsWith(""), and endsWith(""), and contains(""). 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 contains itself!).

The regex engine and String.replace automatically 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:

System.out.println("string".replaceAll(".?", "*$0"));
// "*s*t*r*i*n*g*"

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

  • regular-expressions.info/Dot Matches (Almost) Any Character and Grouping and Backreferences
like image 93
polygenelubricants Avatar answered Dec 04 '22 03:12

polygenelubricants