ホームページ  >  記事  >  Java  >  Java 正規表現を使用して、すべての大文字を文字列の末尾に移動します

Java 正規表現を使用して、すべての大文字を文字列の末尾に移動します

王林
王林転載
2023-08-25 13:21:20947ブラウズ

Java 正規表現を使用して、すべての大文字を文字列の末尾に移動します

部分式「[ ]」は、括弧内に指定されたすべての文字に一致します。したがって、すべての大文字を文字列の末尾に移動するには、次の手順を実行する必要があります。

  • 指定された文字列内のすべての文字を繰り返し処理します。

  • 正規表現「[A-Z]」を使用して、指定された文字列内のすべての大文字と一致します。

  • 特殊文字と残りの文字を 2 つの異なる文字列に連結します。

  • 最後に、特殊文字列を別の文字列に連結します。

例 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。