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