Java Regex删除新行,但保留空格。
对于字符串" \nabc \n 1 2 3 \nxyz "
我需要它成为"abc 1 2 3 xyz"
。
使用此正则表达式str.replaceAll(“((s | \ n)”,“”); 我可以得到“abc123xyz”,但我怎样才能得到它们之间的空格。
你不必使用正则表达式; 你可以使用trim()
和replaceAll()
代替。
String str = " \nabc \n 1 2 3 \nxyz "; str = str.trim().replaceAll("\n ", "");
这将为您提供您正在寻找的字符串。
这将删除所有空格和换行符
String oldName ="2547 789 453 "; String newName = oldName.replaceAll("\\s", "");
这将有效:
str.replaceAll("^ | $|\\n ", "")
如果你真的想用Regex这样做,这可能会为你做到这一点
String str = " \nabc \n 1 2 3 \nxyz "; str = str.replaceAll("^\\s|\n\\s|\\s$", "");
这是一个非常简单明了的例子,说明我将如何做到这一点
String string = " \nabc \n 1 2 3 \nxyz "; //Input string = string // You can mutate this string .replaceAll("(\s|\n)", "") // This is from your code .replaceAll(".(?=.)", "$0 "); // This last step will add a space // between all letters in the // string...
您可以使用此示例来validation最后一个正则表达式是否有效:
class Foo { public static void main (String[] args) { String str = "FooBar"; System.out.println(str.replaceAll(".(?=.)", "$0 ")); } }
输出:“F oo B ar”
有关正则表达式中的外观的更多信息,请访问: http : //www.regular-expressions.info/lookaround.html
这种方法使得它可以在任何字符串输入上工作,它只是在原始工作上添加了一个步骤,以便准确地回答您的问题。 快乐编码:)