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

使用Java正则表达式RegEx将所有特殊字符移动到字符串的末尾)

ي匹配 هذا التعبير النصي جميع الأحرف الخاصة، أي جميع الأحرف غير الأبجدية الإنجليزية والرقمية والفضاءات والمحاور.

"[^a-zA-Z0-9\\s+]"

لتحريك جميع الأحرف الخاصة إلى نهاية السطر المحدد، استخدم هذا التعبير النصي لإيجاد جميع الأحرف الخاصة كنص فارغ، ثم قم بدمج البقية من الأحرف في نص آخر ودمج هذين النصين.

مثال 1

public class RemovingSpecialCharacters {
   public static void main(String args[]) {
      String input = "sample # text * with & special@ characters";
      String regex = "[^a-zA-Z0-9\\s+]";
      String specialChars = "";
      String inputData = "";
      للدوران (int i = 0; i < input.length(); i++) {
         حرف ch = input.charAt(i);
         if(String.valueOf(ch).matches(regex)) {
            specialChars = specialChars + ch;
         } else {
            inputData = inputData + ch;
         }
      }
      System.out.println("نتيجة: " + inputData + specialChars);
   }
}

نتيجة الخروج

نتيجة: نص عادي يحتوي على أحرف خاصة #*&@

مثال 2

هذا برنامج Java، يستخدم طريقة حزمة Regex لتحريك الأحرف الخاصة إلى نهاية النص.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String args[]) {
      String input = "sample # text * with & special@ characters";
      String regex = "[^a-zA-Z0-9\\s+]";
      String specialChars = "";
      System.out.println("الخط النصي المدخل:\n"+input);
      //إنشاء نموذج
      Pattern pattern = Pattern.compile(regex);
      //التنسيق للعثور على النمط المسبق
      Matcher matcher = pattern.matcher(input);
      //إنشاء منطقية من النصوص الفارغة
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         specialChars = specialChars+matcher.group();
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("نتيجة:\n"+ sb.toString()+specialChars );
   }
}

نتيجة الخروج

الخط النصي المدخل:
sample # text * with & special@ characters
نتيجة:
text sample with special characters#*&@