Java 正则表达式程序匹配括号"("或")"。
javaobject oriented programmingprogramming更新于 2025/7/13 11:56:17
以下正则表达式接受带括号 − 的字符串
"^.*[\(\)].*$";
^ 匹配句子的开头。
.* 匹配零个或多个(任意)字符。
[\(\)] 匹配括号。
$ 表示句子的结尾。
示例 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 = "^.*[\(\)].*$";
//读取用户输入
Scanner sc = new Scanner(System.in);
System.out.println("Enter data: ");
String input = sc.nextLine();
//实例化 Pattern 类
Pattern pattern = Pattern.compile(regex);
//实例化 Matcher 类
Matcher matcher = pattern.matcher(input);
//验证是否发生匹配
if(matcher.find()) {
System.out.println("Input received");
}else {
System.out.println("Not received");
}
}
}
输出 1
输入数据: sample(text) with parenthesis 输入已接受
输出 2
输入数据: sample text 未接受
示例 2
import java.util.Scanner;
public class Example {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("输入电子邮件地址:");
Scanner sc = new Scanner(System.in);
String e_mail = sc.nextLine();
//正则表达式
String regex = "^.*[\(\)].*$";
boolean result = e_mail.matches(regex);
if(result) {
System.out.println("Valid match");
} else {
System.out.println("无效匹配");
}
}
}
输出 1
输入电子邮件地址: sample(text) with parenthesis 有效匹配
输出 2
输入电子邮件地址: sample text 无效匹配
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

