小言_互联网的博客

Java正则表达式匹配一句英文句子(大写字母开头,结尾有句号)

847人阅读  评论(0)

正则表达式:

[A-Za-z]+[A-Za-z0-9_,"#;.() \s]*[.]$

或

^([A-Z]){1}[^.]*.

测试代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Contain_Test {
    public static void main(String[] args) {
        String example1="I am a handsome boy.";
        String example2="Where there is a will, there is a way.";
        String regex="[A-Za-z]+[A-Za-z0-9_,\"#;.() \\s]*[.]$";//匹配一句英文语句。
        String anotherRegex="^([A-Z]){1}[^.]*.";
        Pattern pattern=Pattern.compile(regex);
        Pattern anotherPattern=Pattern.compile(anotherRegex);
        Matcher matcher1=pattern.matcher(example1);
        Matcher matcher2=pattern.matcher(example2);
        Matcher matcher3=anotherPattern.matcher(example1);
        Matcher matcher4=anotherPattern.matcher(example2);
        boolean result1=matcher1.matches();
        boolean result2=matcher2.matches();
        boolean result3=matcher3.matches();
        boolean result4=matcher4.matches();
        System.out.println("regex's result:");
        System.out.println(example1+"  =>"+result1);
        System.out.println(example2+"  =>"+result2);
        System.out.println("anotherRegex's result:");
        System.out.println(example1+"  =>"+result3);
        System.out.println(example2+"  =>"+result4);
    }
}

 

测试结果:

regex's result:
I am a handsome boy.  =>true
Where there is a will, there is a way.  =>true

anotherRegex's result:
I am a handsome boy.  =>true
Where there is a will, there is a way.  =>true

 


转载:https://blog.csdn.net/qq_38890412/article/details/102491165
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场