I have a string, for ex:
There exists a word *random*.
random will be a random word.
How can I use a regular expression to replace every character of random with * and have this result:
There exists a word ********.
So the * replaces every character, in this case 6 characters.
Notice that I am after to replace only the word random, not the surroundings *.
So far I have:
str.replaceAll("(\\*)[^.]*(\\*)", "\\*");
But it replaces *random* with *, instead of the desired ******** (total of 8).
Any help, really appreciated…
If you have just a single word like that: –
As far as current example is concerned, if you are having just a single word like that, then you can save yourself from regex, by using some
Stringclass methods: –If you can have multiple words like that: –
For that, here’s a regex solution (This is where it starts getting a little complex): –
The above pattern replaces all the characters that is not followed by
string containing even numbers of *till the end, with a*.Whichever is appropriate for you, you can use.
I’ll add an explanation of the above regex: –
Now the above pattern will match only those words, which are
inside a pair of stars. Provided you don’t have any unbalancedstars.