正则表达式

来源:互联网 发布:云购源码下载 编辑:程序博客网 时间:2024/06/15 10:42

常用的正则表达式
[abc] a,b或者c
[^abc] 除了abc
[a-zA-Z]a到z或者A到Z

\d 数字:[0-9]
\D 非数字:[^0-9]
\s 空白字符
\S 非空白字符
\w 单词字符[a-zA-Z_0-9]
\W 非单词字符

import java.util.regex.Matcher;import java.util.regex.Pattern;import org.junit.Test;public class RegexMatches {    /**     *X{n,m} X至少出现n次小于m次     */    public static void main(String args[]) {        String str = "123456701";        String pattern = "[1-9][0-9]{4,14}";        Pattern r = Pattern.compile(pattern);        Matcher m = r.matcher(str);        System.out.println(m.matches());    }    /**     * X? X,一次或者一次也没有     */    @Test    public void test(){        String str = "aoob";        String pattern = "ao?b";        Pattern r = Pattern.compile(pattern);        Matcher m = r.matcher(str);        System.out.println(m.matches());    }    /**     * 一次或者多次     */    @Test    public void test1(){        String str = "aoob";        String pattern = "ao+b";        Pattern r = Pattern.compile(pattern);        Matcher m = r.matcher(str);        System.out.println(m.matches());    }    /**     * 零次或者多次     */    @Test    public void test2(){        String str = "ab";        String pattern = "ao*b";        Pattern r = Pattern.compile(pattern);        Matcher m = r.matcher(str);        System.out.println(m.matches());    }    /**     * X{n,}至少n次     */    @Test    public void test3(){        String str = "aoooooooob";        String pattern = "ao{4,}b";        Pattern r = Pattern.compile(pattern);        Matcher m = r.matcher(str);        System.out.println(m.matches());    }    /**     * X{4,6}至少4次但是不超过6次     */    @Test    public void test4(){        String str = "aoooooooooooob";        String pattern = "ao{4,6}b";        Pattern r = Pattern.compile(pattern);        Matcher m = r.matcher(str);        System.out.println(m.matches());    }}
原创粉丝点击