Java使用正则表达式从字符串中删除模式

D.S*_*fer 6 java regex

我需要从以下子字符串中清除我的字符串:

\n

\uXXXXX是数字或字符)

例如 "OR\n\nThe Central Site Engineering\u2019s \u201cfrontend\u201d, where developers turn to"

-> "OR The Central Site Engineering frontend , where developers turn to"
我尝试使用String方法replaceAll,但dnt知道如何克服\ uXXXX问题,以及它不适用于\ n

String s = "\\n";  
data=data.replaceAll(s," ");
Run Code Online (Sandbox Code Playgroud)

这个正则表达式在Java中的外观如何?

谢谢您的帮助

Psh*_*emo 7

问题string.replaceAll("\\n", " ");在于replaceAll期望正则表达式,而\regex中的特殊字符用于创建例如\d代表数字的字符类,或转义regex特殊字符(例如)+

因此,如果要\在Javas正则表达式中进行匹配,则需要对其进行两次转义:

  • 一次在正则表达式中 \\
  • 还有一次在String中"\\\\"

喜欢replaceAll("\\\\n"," ")

您还可以让正则表达式引擎为您转义并使用replace类似的方法

replace("\\n"," ")

现在要删除,\uXXXX我们可以使用

replaceAll("\\\\u[0-9a-fA-F]{4}","")


还要记住,字符串是不可变的,因此每个str.replace..调用都不会影响str值,但是会创建新的字符串。因此,如果要将新字符串存储在其中str,则需要使用

str = str.replace(..)
Run Code Online (Sandbox Code Playgroud)

所以你的解决方案看起来像

String text = "\"OR\\n\\nThe Central Site Engineering\\u2019s \\u201cfrontend\\u201d, where developers turn to\"";

text = text.replaceAll("(\\\\n)+"," ")
           .replaceAll("\\\\u[0-9A-Ha-h]{4}", "");
Run Code Online (Sandbox Code Playgroud)


Roe*_*erg 0

我想最好分两部分来做:

String ex = "OR\n\nThe Central Site Engineering\u2019s \u201cfrontend\u201d, where developers turn to";
String part1 = ex.replaceAll("\\\\n"," "); // The firs \\ replaces the backslah, \n replaces the n.
String part2 = part1.replaceAll("u\\d\\d\\d\\d","");
System.out.println(part2);
Run Code Online (Sandbox Code Playgroud)

尝试一下=)