Java: match regex and replace each character
I have a string, for example:
There exists a word *random*.
Random will be a random word How to replace each random character * with a regular expression and get the following results:
There exists a word ********.
So * replaces each character, in this case 6 characters Please note that I only change random words later, not the surrounding * So far, I have:
str.replaceAll("(\\*)[^.]*(\\*)","\\*");
But it replaces * random * with * instead of the required ******* (8 in total) I really appreciate any help
Solution
If you have only one word: –
In the current example, if you have only one such word, you can protect yourself from regular expressions by using some string class methods: –
String str = "There exists a word *random*.";
int index1 = str.indexOf("*");
int index2 = str.indexOf("*",index1 + 1);
int length = index2 - index1 - 1; // Get length of `random`
StringBuilder builder = new StringBuilder();
// Append part till start of "random"
builder.append(str.substring(0,index1 + 1));
// Append * of length "random".length()
for (int i = 0; i < length; i++) {
builder.append("*");
}
// Append part after "random"
builder.append(str.substring(index2));
str = builder.toString();
If you can have such multiple words: –
To this end, this is a regular expression solution (which is where it starts to get a little complicated): –
String str = "There exists a word *random*.";
str = str.replaceAll("(?<! ).(?!([^*]*[*][^*]*[*])*[^*]*$)","*");
System.out.println(str);
The above pattern replaces all characters that do not follow a string containing an even number * with * until the end
Whatever suits you, you can use it
I'll add an explanation of the above regular expression: –
(?<! ) // Not preceded by a space - To avoid replacing first `*`
. // Match any character
(?! // Not Followed by (Following pattern matches any string containing even number of stars. Hence negative look-ahead
[^*]* // 0 or more Non-Star character
[*] // A single `star`
[^*]* // 0 or more Non-star character
[*] // A single `star`
)* // 0 or more repetition of the prevIoUs pattern.
[^*]*$ // 0 or more non-star character till the end.
Now the above pattern matches only those words in a pair of stars As long as you don't have any unbalanced stars
