java匹配或_Java正则表达式程序以匹配括号“(”或“)”。以下正则表达式接受带括号的字符串-"^.*[\\(\\)].*$";^匹配句⼦的开头。
。*匹配零个或多个(任何)字符。
[\\(\\)]匹配的括号。
$表⽰句⼦的结尾。
例⼦1import java.util.Scanner;
import Matcher;
import 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 = Patternpile(regex);
//实例化Matcher类
Matcher matcher = pattern.matcher(input);
//验证是否发⽣匹配
if(matcher.find()) {
System.out.println("Input accepted");
}else {
System.out.println("Not accepted");
}
}
}
输出1Enter data:
sample(text) with parenthesis
Input accepted
输出2Enter data:
sample text
Not accepted
例⼦2import java.util.Scanner;
public class Example {
public static void main(String args[]) {
//从⽤户读取字符串
System.out.println("Enter email address: "); 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("Invalid match");
}
}
}
输出1Enter email address:
sample(text) with parenthesis
Valid match
输出2Enter email address:
sample text
Invalid match
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论