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

Explication de l'expression régulière \ s en Java

Expression sous-jacente/Le caractère de métacaractère " \ s" est équivalent à l'espace.

Exemple1

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("Nombre de correspondances: "+count);
   }
}

Résultat de la sortie

Nombre de correspondances: 7

Exemple2

Le siguiente ejemplo lee una cadena y elimina todos los espacios innecesarios entre ellas.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Lire une chaîne de l'utilisateur
      System.out.println("Entrez une chaîne");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Expression régulière pour correspondre aux espaces (un ou plusieurs)
      String regex = "\\s"+";
      //Compiler l'expression régulière
      Pattern pattern = Pattern.compile(regex);
      //Récupérer l'objet du mécanisme de correspondance
      Matcher matcher = pattern.matcher(input);
      //Remplacer toutes les espaces par un espace unique
      String result = matcher.replaceAll(" ");
      System.out.print("Texte après suppression des espaces indésirables: \n");+result);
   }
}

Résultat de la sortie

Entrez une chaîne
hello this is a sample text with irregular spaces
Texte après suppression des espaces indésirables:
hello this is a sample text with irregular spaces
Vous pourriez aussi aimer