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

مثال على طريقة replaceAll() في Java

استيراد java.util.Scanner;
استيراد java.util.regex.Matcher;
استيراد java.util.regex.Pattern;
public class ReplaceAllExample {
   
      Scanner sc = new Scanner(System.in);
      
      String input = sc.nextLine();
      
      
      Pattern pattern = Pattern.compile(regex);
      
      Matcher matcher = pattern.matcher(input);
      
      
         
      }
      
      System.out.println("هناك
      //استبدال جميع الأحرف الخاصة [#[%&*]] بأية! String result = matcher.replaceAll("!");
      System.out.println("تم استبدال جميع الأحرف الخاصة [#[%&*]] بأية! \n"+result);
   }
}

نتيجة الخروج

أدخل النص المدخل:
مرحبا#[كيف]#[أنت] *&مرحباً بك في T#[Tutorials]%point
هناك 7 أحرف خاصة [#[%&*]] في النص المقدم
تم استبدال جميع الأحرف الخاصة [#[%&*]] بأية!
مرحبا! كيف حالك! مرحباً بك في T!utorials!point

مثال2

استيراد java.util.Scanner;
استيراد java.util.regex.Matcher;
استيراد java.util.regex.Pattern;
public class ReplaceAllExample {
   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