English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Интерпретация мета-символа \s в Java

Подразделение/метасимвол "\s" эквивалентно пробелу.

Пример 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main(String args[]) {
      String regex = "\\s";
      String input = "您好,欢迎来到w3codebox!";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}

Результат вывода

Number of matches: 7

Пример 2

Ниже приведен пример, который читает строку и удаляет все избыточные пробельные символы между ними.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Чтение строки от пользователя
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Регулярное выражение для匹配 пробельных символов (один или несколько)
      String regex = "\\s+";
      //Компилировать регулярное выражение
      Pattern pattern = Pattern.compile(regex);
      //Извлечь объект маркера
      Matcher matcher = pattern.matcher(input);
      //Заменить все пробельные символы одним пробельным символом
      String result = matcher.replaceAll(" ");
      System.out.print("Text after removing unwanted spaces: \n"+result);
   }
}

Результат вывода

Enter a String
hello this is a sample text with irregular spaces
Text after removing unwanted spaces:
hello this is a sample text with irregular spaces
Вам может понравиться