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

كيفية إزالة الفراغات باستخدام العناصر النمطية Java (RegEx)؟

تعبير النمط "\\s" يتطابق مع الفراغات في النص.replaceAll()الطريقة تستقبل نصًا وتستخدم تعبيرًا نموذجيًا لتغيير الرموز التي تتطابق مع التمويه. إذا كنت ترغب في إزالة جميع الفراغات من النص المدخل، فأنت بحاجة إلى تجنب التعبير النموذجي المذكور أعلاه وكتابة سلسلة فارغة كمدخل، ثم إدخالها فيreplaceAll()الطريقة.

مثال 1

public class RemovingWhiteSpaces {
   public static void main( String args[] ) {
      String input = "Hi welcome to w3codebox";
      String regex = "\\s";
      String result = input.replaceAll(regex, "");
      System.out.println("نتيجة: "+result);
   }
}

نتيجة الخروج

النتيجة: Hiwelcometow3codebox

مثال 2

مثل ذلك،appendReplacement()يستقبل الطريقة منطقًا يحتوي على منطق سلسلة وتمويه ويضيف الرموز التي تتطابق مع التمويه باستخدام تمويه معين ويضيفها إلى منطق سلسلة.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemovingWhiteSpaces {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("ادخل نص المدخل: ");
      String input = sc.nextLine();
      String regex = "\\s";
      String constants = "";
      System.out.println("النص المدخل: \n"+input);
      //إنشاء نموذج نمط
      نمط نمط = نمط.compile(التعبير_النموذجي);
      // تطابق النمط المسبق للنص
      Matcher matcher = pattern.matcher(input);
      // إنشاء مساحة نصية فارغة
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         constants = constants+matcher.group();
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("نتيجة: 
"+ sb.toString()+constants );
   }
}

نتيجة الخروج

أدخل سلسلة الإدخال:
this is a sample text with white spaces
Input string:
this is a sample text with white spaces
نتيجة:
thisisasampletextwithwhitespaces

مثال 3

public class Just {
   public static void main(String args[]) {
      String input = "This is a sample text with spaces";
      String str[] = input.split(" ");
      String result = "";
      for(int i=0; i<str.length; i++) {
         result = result+str[i];
      }
      System.out.println("نتيجة: "+result);
   }
}

نتيجة الخروج

نتيجة: This is a sample text with spaces
سيحبك