java使用正则表示式限制特殊字符的个数

package com.l.dubbo.service;

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

public class ThreadPoolTest {
    public static boolean check1(String context, String regEx) {
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(context);
        String ss = "";
        String s2 = "";
        boolean flag = true;
        int count = 0;
        //符合正则表达式的子段为特殊符号
        //比较子段是否重复  若重复则特殊符号种类不止一种
        while (matcher.find()) {
            if (count == 0) {
                ss = matcher.group();
//                System.out.println(ss);
            } else {
                s2 = matcher.group();
//                System.out.println(s2);
            }
            if (!(ss).equals(s2) && count > 0) {
                flag = false;
            }
            count++;
        }
//        System.out.println(count);
        return flag;
    }

    public static boolean check2(String context, String regEx) {
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(context);
        boolean flag = false;
        //利用set的元素不能重复,来检查是否只有一种特殊符号
        Set set = new HashSet();
        while (matcher.find()) {
            set.add(matcher.group());
        }
        if (set.size() == 1) {
            flag = true;
        }
        return flag;
    }

    public static void main(String[] args) {
        //s1中只包含’!‘一种特殊字符
        String s1 = "dasd!a22!!!!";
        //s2中包含’!‘和’@‘两种特殊字符
        String s2 = "dasd!a22@!!!";
        String regEx = "((?=[\\x21-\\x7e]+)[^A-Za-z0-9])";
        System.out.println(check1(s1, regEx));
        System.out.println(check1(s2, regEx));
        System.out.println(check2(s1, regEx));
        System.out.println(check2(s2, regEx));
    }
}

输出结果

true
false
true
false

Process finished with exit code 0

 

你可能感兴趣的:(Java)