括弧(または、)に一致するJava正規表現プログラム。
次の正規表現は、括弧付きの文字列を受け入れます-
"^.*[\\(\\)].*$";
-
^は文の先頭に一致します。
-
。*0個以上の(任意の)文字に一致します。
-
[\\(\\)]一致する括弧。
-
$は文の終わりを示します。
例1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleTest {
public static void main( String args[] ) {
String regex = "^.*[\\(\\)].*$";
//Reading input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter data: ");
String input = sc.nextLine();
//Instantiating the Pattern class
Pattern pattern = Pattern.compile(regex);
//Instantiating the Matcher class
Matcher matcher = pattern.matcher(input);
//verifying whether a match occurred
if(matcher.find()) {
System.out.println("Input accepted");
}else {
System.out.println("Not accepted");
}
}
} 出力1
Enter data: sample(text) with parenthesis Input accepted
出力2
Enter data: sample text Not accepted
例2
import java.util.Scanner;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter email address: ");
Scanner sc = new Scanner(System.in);
String e_mail = sc.nextLine();
//Regular expression
String regex = "^.*[\\(\\)].*$";
boolean result = e_mail.matches(regex);
if(result) {
System.out.println("Valid match");
} else {
System.out.println("Invalid match");
}
}
} 出力1
Enter email address: sample(text) with parenthesis Valid match
出力2
Enter email address: sample text Invalid match
-
JavaRegExを使用して任意の文字を照合する方法
メタ文字「。」 Javaの正規表現は、任意の文字(単一)に一致します。アルファベット、数字、または任意の特殊文字にすることができます。 例1 import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Reading String from user
-
文字列内の母音をカウントするJavaプログラム
以下が私たちの文字列だとしましょう- String myStr = "Jamie"; 同じ変数の母音を計算するので、変数count=0に設定します。すべての文字をループして母音を数えます- for(char ch : myStr.toCharArray()) { ch = Character.toLowerCase(ch); if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u