首頁  >  文章  >  Java  >  使用Java正規表示式將所有大寫字母移到字串的末尾

使用Java正規表示式將所有大寫字母移到字串的末尾

王林
王林轉載
2023-08-25 13:21:20947瀏覽

使用Java正規表示式將所有大寫字母移到字串的末尾

子表達式 “[ ]” 符合括號中指定的所有字元。因此,要將所有大寫字母移動到字串的末尾,需要執行以下步驟:

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

  • 使用正規表示式 "[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

以下是使用Regex 套件的方法將字串的大寫字母移到末尾的Java 程式。

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

以上是使用Java正規表示式將所有大寫字母移到字串的末尾的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除