gpt4 book ai didi

java - 匹配字符串 ÷x% 的正则表达式

转载 作者:行者123 更新时间:2023-12-02 10:56:17 25 4
gpt4 key购买 nike

我一直在尝试创建一个与以下模式匹配的正则表达式:

÷x%

这是我的代码:

String string = "÷x%2%x#3$$@";
String myregex = "all the things I've tried";
string = string.replaceAll(myregex,"÷1x#1$%");

我尝试过以下正则表达式:(÷x%) 、 [÷][x][%] 、 [÷]{1}[x]{1}[%]{1}

我正在使用 NetBeans IDE,它为我提供了一个

Illegal group reference

但是,当我将字符串的值更改为其他内容(例如单词)时。

NetBeans 也不异常(exception)。

任何想法,谢谢

最佳答案

要替换所有出现的子字符串,您不需要模式。您可以使用String.replace() :

String input = "÷x%abc÷x%def÷x%";
String output = input.replace("÷x%", "÷1x#1$%");
System.out.println(output); // ÷1x#1$%abc÷1x#1$%def÷1x#1$%

根据 javadoc 方法:

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

关于java - 匹配字符串 ÷x% 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51705235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com