gpt4 book ai didi

java - String.replaceFirst 错误? java

转载 作者:行者123 更新时间:2023-12-01 07:19:40 28 4
gpt4 key购买 nike

当我这样做的时候

String s = "2r2";
System.out.println(s.replaceFirst("2r2","4"));

它有效,打印 4,但是当我这样做时

String s = "2^2";
System.out.println(s.replaceFirst("2^2","4"));

它不起作用(它打印 2^2),为什么?我该怎么办?

最佳答案

replaceFirst 使用正则表达式语法,其中 ^ 具有特殊含义(它表示字符串或行的开头,具体取决于所使用的修饰符)。

您需要像 "2\\^2" 一样转义 ^,或者为了让您的生活更简单,请使用 Pattern.quote("2^2") 为您执行此操作。

所以你的代码应该更像是:

String s = "2^2";
System.out.println(s.replaceFirst(Pattern.quote("2^2"),"4"));

关于java - String.replaceFirst 错误? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43968109/

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