Java正規表現RegExを使用して、すべての特殊文字を文字列の末尾に移動します)
次の正規表現は、すべての特殊文字、つまり英語のアルファベットのスペースと数字を除くすべての文字に一致します。
"[^a-zA-Z0-9\\s+]"
すべての特殊文字を指定された行の終わりに移動するには、この正規表現を使用してすべての特殊文字を一致させ、それらを空の文字列に連結し、残りの文字を別の文字列に連結し、最後にこれら2つの文字列を連結します。
例1
public class RemovingSpecialCharacters {
public static void main(String args[]) {
String input = "sample # text * with & special@ characters";
String regex = "[^a-zA-Z0-9\\s+]";
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 special characters#*&@
例2
以下は、正規表現パッケージのメソッドを使用して文字列の特殊文字を最後まで移動するJavaプログラムです。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String input = "sample # text * with & special@ characters";
String regex = "[^a-zA-Z0-9\\s+]";
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 # text * with & special@ characters Result: sample text with special characters#*&@
-
Pythonの正規表現を使用して、文字列内のすべての数値を検索します
テキストから数字のみを抽出することは、Pythonデータ分析で非常に一般的な要件です。これは、Python正規表現ライブラリを使用して簡単に実行できます。このライブラリは、サブストリングとして抽出できる数字のパターンを定義するのに役立ちます。 例 以下の例では、reモジュールの関数findall()を使用しています。これらの関数のパラメーターは、抽出するパターンと抽出する文字列です。以下の例では、小数点や負の符号ではなく、数字のみが取得されることに注意してください。 import re str=input("Enter a String with numbers: \n"
-
正規表現を使用してPythonで文字列の最後に一致させる方法は?
次のコードは、文字列の最後にある「スタジアム」という単語と一致します。「サッカースタジアムのチアリーダー」 $-文字列の末尾に一致します 例 import re s = 'cheer leaders at the football stadium' result = re.search(r'\w+$', s) print result.group() 出力 これにより、出力が得られます stadium