加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java:与Regex匹配并替换每个字符

发布时间:2020-12-15 08:50:12 所属栏目:Java 来源:网络整理
导读:我有一个字符串,例如: There exists a word *random*. 随机将是一个随机的单词. 如何使用正则表达式替换随机的每个字符*并得到以下结果: There exists a word ********. 因此*替换每个字符,在这种情况下为6个字符. 请注意,我之后只更换随机字,而不是周围环
我有一个字符串,例如:

There exists a word *random*.

随机将是一个随机的单词.
如何使用正则表达式替换随机的每个字符*并得到以下结果:

There exists a word ********.

因此*替换每个字符,在这种情况下为6个字符.
请注意,我之后只更换随机字,而不是周围环境*.
到目前为止,我有:

str.replaceAll("(*)[^.]*(*)","*");

但它用*替换* random *,而不是所需的********(总共8).
任何帮助,真的很感激……

解决方法

如果你只有这样一个词: –

就目前的例子而言,如果你只有一个这样的单词,那么你可以通过使用一些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);

上面的模式用*替换所有未跟随包含偶数*的字符串的字符,直到结尾.

无论哪种适合您,您都可以使用.

我将添加上述正则表达式的解释: –

(?<! )       // 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.

现在上面的模式只匹配那些在一对恒星内的单词.只要你没有任何不平衡的星星.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读