すべてのスペースと句読点で文字列を分割するJava正規表現プログラム。
正規表現「[!._、'@?// s]」は、すべての句読点とスペースに一致します。
例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main( String args[] ) {
String input = "This is!a.sample"text,with punctuation!marks";
Pattern p = Pattern.compile("[!._,'@?//s]");
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
} 出力
Number of matches: 8
split() Stringクラスのメソッドは、正規表現を表す値を受け入れ、現在の文字列をトークン(単語)の配列に分割し、2つの一致が発生する間の文字列を1つのトークンとして扱います。
たとえば、このメソッドの区切り文字として単一のスペース ""を渡し、文字列を分割しようとしたとします。このメソッドは、2つのスペースの間の単語を1つのトークンと見なし、現在の文字列内の単語の配列(スペースの間)を返します。
したがって、すべてのスペースと句読点で文字列を分割するには、上記で指定した正規表現をパラメーターとして渡して、文字列でsplit()メソッドを呼び出します。
例
import java.util.Scanner;
import java.util.StringTokenizer;
public class RegExample {
public static void main( String args[] ) {
String regex = "[!._,'@? ]";
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
StringTokenizer str = new StringTokenizer(input,regex);
while(str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
} 出力
Enter a string: This is!a.sample text,with punctuation!marks@and_spaces This is a sample text with punctuation marks and spaces
-
文字列を取り込んですべての空白スペースをハイフンに置き換えるPythonプログラム
文字列を取得し、すべての空白スペースをハイフンで置き換える必要がある場合は、「replace」メソッドを使用できます。空白スペースと、置き換える必要のある値(この場合はハイフン)の2つのパラメーターを取ります。 以下は同じのデモンストレーションです- 例 my_string = input("Enter a string :") print("The string entered by user is :") print(my_string) my_string = my_string.replace(' ','-')
-
文字列を分割して結合するPythonプログラム?
Pythonプログラムは、文字列の結合と文字列の分割のための組み込み関数を提供します。 split Str.split() join Str1.join(str2) アルゴリズム Step 1: Input a string. Step 2: here we use split method for splitting and for joining use join function. Step 3: display output. サンプルコード #split of string str1=input(Enter first String with space :: ) prin