如何解决我无法使用正则表达式替换包含“\”字符的文本
我有一个片段
public static void main(String[] args) {
// replacement text
String replacement = "Not Set";
// text
String text = "Item A \\(XXX\\) Lock"; // text is "Item A\(XXX\)Lock"
String regex = "\\(XXX\\)"; // regex is "\(XXX\)"
// result text
String resultText = text.replaceAll(regex,replacement);
System.out.println("Result text: " + resultText);
}
resultText 是“Item A \(XXX\) Lock” -> 我无法将“\(XXX\)”替换为“Not Set”。
如果你知道这个问题,请帮助我。
解决方法
正则表达式语言在 Java 字符串文字转义序列之上有自己的转义序列。因此,要匹配反斜杠,您需要在正则表达式中使用 Using built-in specs.
COLLECT_GCC=/usr/local/bin/gfortran
COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc/10.2.0_2/libexec/gcc/x86_64-apple-darwin19/10.2.0/lto-wrapper
Target: x86_64-apple-darwin19
Configured with: ../configure --build=x86_64-apple-darwin19 --prefix=/usr/local/Cellar/gcc/10.2.0_2 --libdir=/usr/local/Cellar/gcc/10.2.0_2/lib/gcc/10 --disable-nls --enable-checking=release --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-10 --with-gmp=/usr/local/opt/gmp --with-mpfr=/usr/local/opt/mpfr --with-mpc=/usr/local/opt/libmpc --with-isl=/usr/local/opt/isl --with-system-zlib --with-pkgversion='Homebrew GCC 10.2.0_2' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --disable-multilib --with-native-system-header-dir=/usr/include --with-sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk SED=/usr/bin/sed
Thread model: posix
Supported LTO compression algorithms: zlib
gcc version 10.2.0 (Homebrew GCC 10.2.0_2)
,因此在 Java 字符串文字中需要 var sInput = '{"a" : 1,"b" : [2,3,4]}';
var json = Fiddler.WebFormats.JSON.JsonDecode(sInput);
在这种情况下,您也可以使用 Pattern.quote
\\
,
字符 \
、(
和 )
在正则表达式中使用时都有特殊的含义。但是您不想使用它们的特殊含义,这意味着您必须在正则表达式中对它们进行转义。这意味着在它们前面加上 \
,告诉正则表达式处理器不要调用这些字符的特殊含义。
换句话说,包含\\
的正则表达式将匹配\
,包含
\(
将匹配 (
等。
要匹配 \(XXX\)
,您想要的正则表达式将是 \\\(XXX\\\)
- 看看每个 \
、\
和 {{ 如何有一个额外的 (
1}} 你想匹配。但是要在 Java )
文字中指定此正则表达式,您需要编写 String
来代替每个 \\
。也就是说,你需要写
\
。它们的每一小段都有六个 "\\\\\\(XXX\\\\\\)"
字符。
\
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。