正则表达式

来源:互联网 发布:淘宝代理货源要钱吗 编辑:程序博客网 时间:2024/06/11 21:19
package com.regex;/** * 满足规则返回true   不满足返回false * 一个范围词没有配合数量词使用也只能匹配一个字符而已 预定义字符类 . 任何字符(与行结束符可能匹配也可能不匹配) \d 数字:[0-9] \D 非数字: [^0-9] \s 空白字符:[ \t\n\x0B\f\r] \S 非空白字符:[^\s] \w 单词字符:[a-zA-Z_0-9] \W 非单词字符:[^\w] * *//** * @author 谢英亮 * @date 2017年12月22日  下午3:08:24 * @Description:  */public class Demo2 {public static void main(String[] args) {String regex=".";System.out.println(".".matches(regex));System.out.println(".1".matches(".."));System.out.println("1".matches("\\."));System.out.println("1".matches("\\d"));System.out.println("1".matches("\\D"));System.out.println("~ ".matches("[^0-9] "));System.out.println("\t".matches("\\s"));System.out.println("_".matches("\\w"));System.out.println("%".matches("[a-zA-Z_0-9$%]"));//. 这个字符   \.     ==>\\.//split("\\|")}}
package com.regex;/**Greedy 数量词X?X,一次或一次也没有  0或1X*X,零次或多次  0  >=1X+X,一次或多次        >=1X{n}X,恰好n次X{n,}X,至少n次X{n,m}X,至少n次,但是不超过m次范围表示[abc]a、b 或 c(简单类) [^abc]任何字符,除了 a、b 或 c(否定) [a-zA-Z]a 到 z 或 A 到 Z,两头的字母包括在内(范围)  * @author 谢英亮 * @date 2017年12月22日  下午3:05:31 * @Description:  */public class Demo3 {public static void main(String[] args) {System.out.println("b".matches("a?"));System.out.println("ab".matches("a?b"));//注意啦System.out.println("a".matches("a*"));//有或者没有System.out.println("aaaaa".matches("a+"));//至少1次System.out.println("aaaaaa".matches("a{5}"));//刚好5次System.out.println("aaaaaa".matches("a{5,}"));//至少5次System.out.println("aaaaaaaaaa".matches("a{5,10}"));//5次到10次  包括5次和10次System.out.println("asdads1234!".matches("[^a-z\\d!]+"));}}

package com.regex;/** * @author 谢英亮 * @date 2017年12月22日  下午3:06:08 * @Description:  */public class DemoReplaceAll {public static void main(String[] args) {String regex="(\\d{3})(\\d{4})(\\d{4})";//引用组的内容System.out.println("13111111111".replaceAll(regex, "$1XXXX00000$3"));//我我我我是是是是是是是是是是高高高富富富富富富富富富富富富帅帅帅===》我是高富帅String gfs="我我我我是是是是是是是是是是高高高富富富富富富富富富富富富帅帅帅";System.out.println(gfs.replaceAll("(.)\\1+", "$1"));String zw="[^\u4e00-\u9fa5]{3,8}";//用户名必须是中文  长度在3-8System.out.println("abced".matches(zw));}}

package com.regex;import java.util.Arrays;/** * @author 谢英亮 * @date 2017年12月22日  下午3:06:35 * @Description: 需求2 :根据重叠词进行切割 */public class DemoSplit {public static void main(String[] args) {/** * + .  *  |  &  \ */String  str="我我我|爱.的|卡哪款.的数据你\\感觉\\聚.精会神实.例化啊速度和";String[] split = str.split("\\\\");System.out.println(Arrays.toString(split));System.out.println("--------------------------------------");String str1="我阿达的我我12是是是啊是的哈看电电视剧啊都是考试的考点阿闪大大多";//后面匹配的要用到上一个匹配的结果//分组/** * ((A)(B(C)))  * 第1组:((A)(B(C))) * 第2组:(A) * 第3组:(B(C)) * 第4组:(C) */String regex="(.)\\1+";System.out.println("123132".matches("1234+"));String[] split2 = str1.split(regex);System.out.println(Arrays.toString(split2));}}


原创粉丝点击