Jim*_*Lee 1 java regex string replace
我想使用 Pattern\ 的编译方法来做到这一点。例如
\n\nString 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("");\nRun Code Online (Sandbox Code Playgroud)\n\n可以完成我想要完成的任务的正则表达式是什么?
\n\n示例字符串:
\n\n英语
\n\nInput: "Where? What is that, an animal? No! It is a plane."\nOutput: "Where What is that an animal No It is a plane"\nRun Code Online (Sandbox Code Playgroud)\n\n西班牙语
\n\nInput: "\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"\nRun Code Online (Sandbox Code Playgroud)\n\n葡萄牙语
\n\nInput: "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"\nRun Code Online (Sandbox Code Playgroud)\n\n希望这些示例能够清楚地说明我想要完成的任务。\n谢谢大家!
\nJavaPattern类是正则表达式的 Java 实现,支持Unicode 类别,例如\\p{Lu}。由于您需要字母数字,因此将是类别 L(字母)和N(数字)。
由于您的示例显示您还想保留空格,因此您需要将其包括在内。让我们使用预定义字符类 \\s,这样您还可以保留换行符和制表符。
要查找除指定字符之外的任何内容,请使用否定字符类:[^abc]
总而言之,这意味着[^\\s\\p{L}\\p{N}]:
String output = input.replaceAll("[^\\\\s\\\\p{L}\\\\p{N}]+", "");\nRun Code Online (Sandbox Code Playgroud)\n\nString output = input.replaceAll("[^\\\\s\\\\p{L}\\\\p{N}]+", "");\nRun Code Online (Sandbox Code Playgroud)\n\n或者参见regex101.com的演示。
\n\n当然,有多种方法可以做到这一点。
\n\n您也可以使用POSIX 字符类 \\p{Alnum},然后启用UNICODE_CHARACTER_CLASS,使用(?U).
String output = input.replaceAll("(?U)[^\\\\s\\\\p{Alnum}]+", "");\nRun Code Online (Sandbox Code Playgroud)\n\nWhere 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\nRun Code Online (Sandbox Code Playgroud)\n\n现在,如果您不需要空格,可以通过使用\\P{xx}来简化:
String output = input.replaceAll("(?U)\\\\P{Alnum}+", "");\nRun Code Online (Sandbox Code Playgroud)\n\nString output = input.replaceAll("(?U)[^\\\\s\\\\p{Alnum}]+", "");\nRun Code Online (Sandbox Code Playgroud)\n