【发布时间】:2018-11-28 20:00:15
【问题描述】:
对于字符串" \n a b c \n 1 2 3 \n x y z ",我需要它变成"a b c 1 2 3 x y z"。
使用这个正则表达式 str.replaceAll("(\s|\n)", "");我可以得到“abc123xyz”,但我怎样才能得到中间的空格。
【问题讨论】:
对于字符串" \n a b c \n 1 2 3 \n x y z ",我需要它变成"a b c 1 2 3 x y z"。
使用这个正则表达式 str.replaceAll("(\s|\n)", "");我可以得到“abc123xyz”,但我怎样才能得到中间的空格。
【问题讨论】:
您不必使用正则表达式;您可以改用trim() 和replaceAll()。
String str = " \n a b c \n 1 2 3 \n x y z ";
str = str.trim().replaceAll("\n ", "");
这将为您提供您正在寻找的字符串。
【讨论】:
这将删除所有空格和换行符
String oldName ="2547 789 453 ";
String newName = oldName.replaceAll("\\s", "");
【讨论】:
这将起作用:
str = str.replaceAll("^ | $|\\n ", "")
【讨论】:
如果你真的想用正则表达式来做这件事,这可能会为你解决问题
String str = " \n a b c \n 1 2 3 \n x y z ";
str = str.replaceAll("^\\s|\n\\s|\\s$", "");
【讨论】:
这是一个非常简单明了的示例,说明我将如何做到这一点
String string = " \n a b c \n 1 2 3 \n x y z "; //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...
您可以使用此示例来验证最后一个正则表达式是否有效:
class Foo {
public static void main (String[] args) {
String str = "FooBar";
System.out.println(str.replaceAll(".(?=.)", "$0 "));
}
}
输出:“F o o B a r”
更多关于正则表达式环视的信息:http://www.regular-expressions.info/lookaround.html
这种方法使它适用于任何字符串输入,并且它只是在您的原始工作上增加了一个步骤,以准确回答您的问题。快乐编码:)
【讨论】: