我想使用 Pattern 的 compile 方法来做到这一点。比如
String text = "Where? What is that, an animal? No! It is a plane.";
Pattern p = new Pattern("*some regex here*");
String delim = p.matcher(text).replaceAll("");
什么正则表达式可以完成我想要完成的任务?
示例字符串:
英语
Input: "Where? What is that, an animal? No! It is a plane."
Output: "Where What is that an animal No It is a plane"
西类牙语
Input: "¿Dónde? ¿Qué es eso, un animal? ¡No! Es un avión."
Output: "Dónde Qué es eso un animal No Es un avión"
葡萄牙语
Input: "Onde? O que é isso, um animal? Não! É um avião."
Output: "Onde O que é isso um animal Não É um avião"
希望这些示例能够清楚地说明我想要实现的目标。 谢谢大家!
最佳答案
Java Pattern
class 是正则表达式的 Java 实现,支持 Unicode Categories ,例如\p{Lu}
。既然你想要字母数字,那就是 Categories L
(字母)和 N
(数字)。
由于您的示例显示您还想保留空格,因此您需要将其包括在内。让我们使用Predefined Character Class \s
,因此您还可以保留换行符和制表符。
要查找除指定字符之外的任何内容,请使用 Negation Character Class :[^abc]
总而言之,这意味着[^\s\p{L}\p{N}]
:
String output = input.replaceAll("[^\\s\\p{L}\\p{N}]+", "");
Where What is that an animal No It is a plane
Dónde Qué es eso un animal No Es un avión
Onde O que é isso um animal Não É um avião
或参见regex101.com用于演示。
<小时/>当然,有多种方法可以做到这一点。
您也可以使用 POSIX Character Class \p{Alnum}
,然后启用UNICODE_CHARACTER_CLASS
,使用 (?U)
。
String output = input.replaceAll("(?U)[^\\s\\p{Alnum}]+", "");
Where What is that an animal No It is a plane
Dónde Qué es eso un animal No Es un avión
Onde O que é isso um animal Não É um avião
<小时/>
现在,如果您不需要空格,可以通过使用 \P{xx}
来简化:
String output = input.replaceAll("(?U)\\P{Alnum}+", "");
WhereWhatisthatananimalNoItisaplane
DóndeQuéesesounanimalNoEsunavión
OndeOqueéissoumanimalNãoÉumavião
关于java - 正则表达式删除所有非字母数字字符并提供通用语言支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45024133/