使用Java正则表达式将所有大写字母移动到字符串的末尾

王林
王林 转载
2023-08-25 13:21:20 502浏览

使用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,如有侵犯,请联系admin@php.cn删除