吾爱乐享
个人学习网站

java之学习正则Greedy 数量词的用法

结果示意图

Greedy 数量词

* X? X,一次或一次也没有
* X* X,零次或多次
* X+ X,一次或多次
* X{n} X,恰好 n 次
* X{n,} X,至少 n 次
* X{n,m} X,至少 n 次,但是不超过 m 次

案例代码

package com.ifenx8.regex;

import javax.print.DocFlavor.STRING;

public class Demo4_Regex {

	/**
	 * A:Greedy 数量词 
		* X? X,一次或一次也没有
		* X* X,零次或多次
		* X+ X,一次或多次
		* X{n} X,恰好 n 次 
		* X{n,} X,至少 n 次 
		* X{n,m} X,至少 n 次,但是不超过 m 次 
	 */
	public static void main(String[] args) {
		demo1();//	X? X,一次或一次也没有
		demo2();//	X* X,零次或多次
		demo3();//	X+ X,一次或多次
		demo4();//	X{n} X,恰好 n 次 
		demo5();//	X{n,} X,至少 n 次 
		String regex = "[abc]{5,14}";//出现5次到14次之间
		System.out.println("abcac".matches(regex));//出现5次,返回true
		System.out.println("abcacaaabbbccc".matches(regex));//出现大于等于5次小于等于14次,返回true
		System.out.println("abcc".matches(regex));//出现4次 不等于5次,返回false
		System.out.println("asdfb".matches(regex));//虽然有5个字符 但是有不包含其中的字符,返回false
		System.out.println("=========");
	}

	public static void demo5() {
		String regex = "[abc]{5,}";//出现5次及5次以上
		System.out.println("abcac".matches(regex));//出现5次,返回true
		System.out.println("abcacaaabbbccc".matches(regex));//出现大于5次,返回true
		System.out.println("abcc".matches(regex));//出现4次 不等于5次,返回false
		System.out.println("asdfb".matches(regex));//虽然有5个字符 但是有不包含其中的字符,返回false
		System.out.println("=========");
	}

	public static void demo4() {
		String regex = "[abc]{5}";//刚好出现5次
		System.out.println("abcac".matches(regex));//出现5次,返回true
		System.out.println("abcacaaabbbccc".matches(regex));//出现大于5次,返回false
		System.out.println("abcc".matches(regex));//出现4次 不等于5次,返回false
		System.out.println("asdfb".matches(regex));//虽然有5个字符 但是有不包含其中的字符,返回false
		System.out.println("=========");
	}

	public static void demo3() {
		String regex = "[abc]+";//表示出现一次或者多次
		System.out.println("a".matches(regex));//出现一次,返回true
		System.out.println("".matches(regex));//出现0次,返回false
		System.out.println("bbbbccc".matches(regex));//出现多次,返回true
		System.out.println("d".matches(regex));//不出现,返回false
		System.out.println("==========");
	}

	public static void demo2() {
		String regex = "[abc]*";//表示出现0次或者多次
			System.out.println("aaaccb".matches(regex));//出现多次,返回true
			System.out.println("a".matches(regex));//出现一次,返回true
			System.out.println("".matches(regex));//出现0次,返回true
			System.out.println("d".matches(regex));//没有出现,返回false
			System.out.println("=========");
	}

	public static void demo1() {
		String regex ="[abc]?";//表示在abc中的一个或者一个也没有
		System.out.println("a".matches(regex));//true
		System.out.println("b".matches(regex));//true
		System.out.println("c".matches(regex));//true
		System.out.println("d".matches(regex));//false
		System.out.println("".matches(regex));//true
		System.out.println("================");
	}

}

赞(0) 打赏
未经允许不得转载:吾爱乐享 » java之学习正则Greedy 数量词的用法

评论 抢沙发

评论前必须登录!

 

推荐免费资源共享,个人经验总结学习

联系我们联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏