正则表达式删除所有非字母数字字符并提供通用语言支持?

Jim*_*Lee 1 java regex string replace

我想使用 Pattern\ 的编译方法来做到这一点。例如

\n\n
String text = "Where? What is that, an animal? No! It is a plane.";\nPattern p = new Pattern("*some regex here*");\nString delim = p.matcher(text).replaceAll("");\n
Run Code Online (Sandbox Code Playgroud)\n\n

可以完成我想要完成的任务的正则表达式是什么?

\n\n

示例字符串:

\n\n

英语

\n\n
Input: "Where? What is that, an animal? No! It is a plane."\nOutput: "Where What is that an animal No It is a plane"\n
Run Code Online (Sandbox Code Playgroud)\n\n

西班牙语

\n\n
Input: "\xc2\xbfD\xc3\xb3nde? \xc2\xbfQu\xc3\xa9 es eso, un animal? \xc2\xa1No! Es un avi\xc3\xb3n."\nOutput: "D\xc3\xb3nde Qu\xc3\xa9 es eso un animal No Es un avi\xc3\xb3n"\n
Run Code Online (Sandbox Code Playgroud)\n\n

葡萄牙语

\n\n
Input: "Onde? O que \xc3\xa9 isso, um animal? N\xc3\xa3o! \xc3\x89 um avi\xc3\xa3o."\nOutput: "Onde O que \xc3\xa9 isso um animal N\xc3\xa3o \xc3\x89 um avi\xc3\xa3o"\n
Run Code Online (Sandbox Code Playgroud)\n\n

希望这些示例能够清楚地说明我想要完成的任务。\n谢谢大家!

\n

And*_*eas 5

JavaPattern类是正则表达式的 Java 实现,支持Unicode 类别,例如\\p{Lu}。由于您需要字母数字,因此将是类别 L(字母)和N(数字)。

\n\n

由于您的示例显示您还想保留空格,因此您需要将其包括在内。让我们使用预定义字符类 \\s,这样您还可以保留换行符和制表符。

\n\n

要查找除指定字符之外的任何内容,请使用否定字符类[^abc]

\n\n

总而言之,这意味着[^\\s\\p{L}\\p{N}]

\n\n
String output = input.replaceAll("[^\\\\s\\\\p{L}\\\\p{N}]+", "");\n
Run Code Online (Sandbox Code Playgroud)\n\n
String output = input.replaceAll("[^\\\\s\\\\p{L}\\\\p{N}]+", "");\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者参见regex101.com的演示。

\n\n
\n\n

当然,有多种方法可以做到这一点。

\n\n

您也可以使用POSIX 字符类 \\p{Alnum},然后启用UNICODE_CHARACTER_CLASS,使用(?U).

\n\n
String output = input.replaceAll("(?U)[^\\\\s\\\\p{Alnum}]+", "");\n
Run Code Online (Sandbox Code Playgroud)\n\n
Where What is that an animal No It is a plane\nD\xc3\xb3nde Qu\xc3\xa9 es eso un animal No Es un avi\xc3\xb3n\nOnde O que \xc3\xa9 isso um animal N\xc3\xa3o \xc3\x89 um avi\xc3\xa3o\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

现在,如果您不需要空格,可以通过使用\\P{xx}来简化:

\n\n
String output = input.replaceAll("(?U)\\\\P{Alnum}+", "");\n
Run Code Online (Sandbox Code Playgroud)\n\n
String output = input.replaceAll("(?U)[^\\\\s\\\\p{Alnum}]+", "");\n
Run Code Online (Sandbox Code Playgroud)\n