【发布时间】:2026-02-05 04:05:01
【问题描述】:
在匹配涉及美元符号的子模式时,我遇到了一些问题。例如,考虑以下文本块:
(en $) foo
oof ($).
ofo (env. 80 $US)
我正在使用以下正则表达式:
Pattern p = Pattern.compile(
"\\([\\p{InARABIC}\\s]+\\)|\\([\\p{InBasic_Latin}\\s?\\$]+\\)|\\)([\\p{InARABIC}\\s]+)\\(",
Pattern.CASE_INSENSITIVE);
public String replace(String text) {
Matcher m = p.matcher(text);
String replacement = m.replaceAll(match -> {
if (m.group(1) == null) {
return m.group();
} else {
return "(" + match.group(1) + ")";
}
});
return replacement;
}
但无法匹配包含$的文本
【问题讨论】:
-
你使用的是
find()还是matches()? -
抱歉忘了说我正在使用匹配器
-
您使用的是
matches还是find?matches不起作用,因为您的字符串与正则表达式不匹配。此外,如果您正确使用find,即使您的第三个样本也不会给您任何东西,因为它里面包含一个.,而您的正则表达式中没有这个 -
regular-expressions.info/charclass.html "通常的元字符是字符类中的普通字符,不需要用反斜杠转义".
-
“如果您转义字符类中的常规元字符,您的正则表达式可以正常工作,但这样做会大大降低可读性。”