如何在 Java 中转义正则表达式中的字符
How to escape a character in Regex expression in Java
我有一个删除所有非字母数字字符的正则表达式。它适用于除 ^ 之外的所有特殊字符。下面是我正在使用的正则表达式。
String strRefernce = strReference.replaceAll("[^\p{IsAlphabetic}^\p{IsDigit}]", "").toUpperCase();
我试过修改为
String strRefernce = strReference.replaceAll("[^\p{IsAlphabetic}^\p{IsDigit}]\^", "").toUpperCase();
和
String strRefernce = strReference.replaceAll("[^\p{IsAlphabetic}^\p{IsDigit}\^]", "").toUpperCase();
但是这些也都无法去掉这个符号。
有人可以帮我解决这个问题吗?
[^...]
中的第一个^
是一个否定标记,使字符class成为否定字符(匹配除内部以外的字符)。
里面的第二个被认为是文字 - 因此,它不应与正则表达式匹配。删除它,插入符号将与其匹配:
"[^\p{IsAlphabetic}\p{IsDigit}]"
甚至更短:
"(?U)\P{Alnum}"
\P{Alnum}
class 代表除 字母数字字符以外的任何字符:[\p{Alpha}\p{Digit}]
(参见 Java regex reference). When you pass (?U)
, the \P{Alnum}
class will not match Unicode letters. See this IDEONE demo。
如果要删除 \p{IsAlphabetic}
和 \p{IsDigit}
.
以外的整块符号,请在末尾添加 +
这也行得通。
System.out.println("Text 尖酸[刻薄 ^, More _0As text °ÑÑ"".replaceAll("(?U)[^[\W_]]+", " "));
输出
Text 尖酸 刻薄 More 0As text Ñ Ñ
不确定,但该词可能是更全面的字母数字字符列表。
[\W_]
是包含非单词和下划线的 class。
当放入负数 Java class 构造时,它变为
[^[\W_]]
是 nothing 和
之间联合的否定 class
class 包含非单词和下划线。
我有一个删除所有非字母数字字符的正则表达式。它适用于除 ^ 之外的所有特殊字符。下面是我正在使用的正则表达式。
String strRefernce = strReference.replaceAll("[^\p{IsAlphabetic}^\p{IsDigit}]", "").toUpperCase();
我试过修改为
String strRefernce = strReference.replaceAll("[^\p{IsAlphabetic}^\p{IsDigit}]\^", "").toUpperCase();
和
String strRefernce = strReference.replaceAll("[^\p{IsAlphabetic}^\p{IsDigit}\^]", "").toUpperCase();
但是这些也都无法去掉这个符号。 有人可以帮我解决这个问题吗?
[^...]
中的第一个^
是一个否定标记,使字符class成为否定字符(匹配除内部以外的字符)。
里面的第二个被认为是文字 - 因此,它不应与正则表达式匹配。删除它,插入符号将与其匹配:
"[^\p{IsAlphabetic}\p{IsDigit}]"
甚至更短:
"(?U)\P{Alnum}"
\P{Alnum}
class 代表除 字母数字字符以外的任何字符:[\p{Alpha}\p{Digit}]
(参见 Java regex reference). When you pass (?U)
, the \P{Alnum}
class will not match Unicode letters. See this IDEONE demo。
如果要删除 \p{IsAlphabetic}
和 \p{IsDigit}
.
+
这也行得通。
System.out.println("Text 尖酸[刻薄 ^, More _0As text °ÑÑ"".replaceAll("(?U)[^[\W_]]+", " "));
输出
Text 尖酸 刻薄 More 0As text Ñ Ñ
不确定,但该词可能是更全面的字母数字字符列表。
[\W_]
是包含非单词和下划线的 class。
当放入负数 Java class 构造时,它变为
[^[\W_]]
是 nothing 和
之间联合的否定 class
class 包含非单词和下划线。