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);
   }
}

نتيجة الخروج

عدد التطابق: 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
توصيات لك