如果你只有一个这样的词:-
就当前示例而言,如果您只有一个这样的单词,那么您可以通过使用一些String
类方法来避免正则表达式:-
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();
如果你可以有多个这样的词:-
为此,这是一个正则表达式解决方案(这是它开始变得有点复杂的地方): -
String str = "There exists a word *random*.";
str = str.replaceAll("(?<! ).(?!([^*]*[*][^*]*[*])*[^*]*$)", "*");
System.out.println(str);
上面的模式string containing even numbers of *
用*
.
哪个适合你,你可以使用。
我将添加对上述正则表达式的解释: -
(?<! ) // 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.
现在上面的模式将只匹配那些单词,它们是inside a pair of stars
. 前提是您没有任何不平衡stars
的 .