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

كيفية استخدام Java RegEx للتوافق مع الفواصل الحرفية؟

الرمز النمطي " \\ s يُطابق رمز النص مع مسافات النص المحدد.

مثال1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = \\\\s;
      //تحرير العبرة النمطية
      Pattern pattern = Pattern.compile(regex);
      //الحصول على كائن المatcher
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("عدد المسافات: " + count);
   }
}

نتيجة الإخراج

ادخل نصًا
مرحبًا how كيف حالك مرحبًا بك في w3codebox
عدد المسافات: 6

مثال2

import java.util.Scanner;
public class RegexExample {
   public static void main( String args[] ) {
      //عبرة نمط
      String regex = "\\s+";
      System.out.println("ادخل قيمة الإدخال: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String result = input.replaceAll(regex, "");
      System.out.println("نتيجة: " + result);
   }
}

نتيجة الإخراج

ادخل قيمة الإدخال:
hello how are you
نتيجة: hellohowareyou
سيحبك هذا