HOWTO · Java
在 Java 中使用 \s
本教程演示了如何在 Java 中使用 \s。
本教程将讨论和演示 Java 中 \\s 的使用。
在 Java 中使用 \s 作为正则表达式
\\s 是 Java 中用于空白字符的正则表达式。正则表达式是用于开发数据模式的字符序列。
当我们在文本中搜索数据时,有时我们会使用模式,而当需要空间时,在这些模式中会使用\\s。
我们使用双反斜杠是因为 Java 语法不支持单反斜杠。实际上,单个空格字符的语法是\s。
例子:
package delftstack;
public class Reg_Expression {
public static final String Demo = "Hello! this is delftstack.com";
public static void main(String[] args) {
// Print the original String
System.out.println("This is the Original String: ");
System.out.println(Demo);
// replace all \\s whitespaces with \t tabs
System.out.println("This is the String \\s replaced with \\t: ");
System.out.println(Demo.replaceAll("\\s", "\t"));
// Split the string at \\s means the spaces
String[] Demo_Split = (Demo.split("\\s"));
System.out.println("This is the String split at \\s: ");
for (String Print_String : Demo_Split) {
System.out.println(Print_String);
}
}
}
上面的代码使用 \\s 操作字符串空格。首先,它用制表符替换空格并在空格处拆分字符串。
输出:
This is the Original String:
Hello! this is delftstack.com
This is the String \s replaced with \t:
Hello! this is delftstack.com
This is the String split at \s:
Hello!
this
is
delftstack.com