Java RegExを使用して、すべての大文字を文字列の末尾に移動する
部分表現「[] 」は、中括弧で指定されたすべての文字に一致します。したがって、すべての大文字を文字列の末尾に移動するには-
-
指定された文字列内のすべての文字を繰り返し処理します。
-
正規表現" [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
以下は、正規表現パッケージのメソッドを使用して文字列の大文字を末尾に移動する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
-
Python Regexを使用して、特定の文字列内の「1(0+)1」のすべてのパターンを検索します
このチュートリアルでは、正規表現を使用して、文字列内の1(0 + 1)のすべての出現を検出するプログラムを作成します。 。 Pythonには、正規表現を操作するのに役立つreモジュールがあります。 1つのサンプルケースを見てみましょう。 Input: string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1" Output: Total number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+
-
Python Regexを使用して、特定の文字列で10+1のすべてのパターンを検索します
与えられた文字列で正規表現パターン10+1を見つける必要があります。このために、Pythonで利用可能なreモジュールを使用できます。このパッケージには、検索する正規表現と文字列を受け入れるfind allというメソッドがあります。これにより、その文字列に出現するすべてのパターンが得られます。たとえば、 入力文字列の場合- 10000001 hello world 10011 test100000001test. 出力を取得する必要があります- 10000001 1001 100000001 次のようにreパッケージを使用して実装できます- import re occ = re.find