使用 Java RegEx 將所有大寫字母移至字串末尾


子表示式 “[ ]” 匹配大括號中指定的所有字元。因此,若要將所有大寫字母移動到字串末尾 −

  • 遍歷給定字串中的所有字元。

  • 使用正則表示式 "[A-Z]" 匹配給定字串中的所有大寫字母。

  • 將特殊字元和剩餘字元連線到兩個不同的字串。

  • 最後,將特殊字元字串連線到另一個字串。

示例 1

public class RemovingSpecialCharacters {
   public static void main(String args[]) {
      String input = "sample B text C with G upper case LM characters in between";
      String regex = "[A-Z]";
      String specialChars = "";
      String inputData = "";
      for(int i=0; i< input.length(); i++) {
         char ch = input.charAt(i);
         if(String.valueOf(ch).matches(regex)) {
            specialChars = specialChars + ch;
         } else {
            inputData = inputData + ch;
         }
      }
      System.out.println("Result: "+inputData+specialChars);
   }
}

輸出

Result: sample text with upper case characters in betweenBCGLM

示例 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 B text C with G upper case LM characters in between";
      String regex = "[A-Z]";
      String specialChars = "";
      System.out.println("Input string: \n"+input);
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      //Creating an empty string buffer
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         specialChars = specialChars+matcher.group();
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("Result: \n"+ sb.toString()+specialChars );
   }
}

輸出

Input string:
sample B text C with G upper case LM characters in between
Result:
sample text with upper case characters in betweenBCGLM

更新於: 2019-11-21

662 次瀏覽

開啟你的事業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.