比如 “253hehehe52”这个字符串,我用正则(he){1}匹配, 结果是true,我的原意是让“he”这个字符串在指定的字符串中只出现一次,那么这时候就表明{1}的意思是看指定字符串中是否出现了1次‘he’,而并不是有且仅有一次,请问用正则如何实现有且仅有一次的功能。
测试代码如下: public static void main(String[] args) {
String regx = "(he){1,2}+";
String date = "55hehe454*2";
Pattern p2 = Pattern.compile(regx);
Matcher m2 = p2.matcher(date);
if(m2.find()){
//格式正确
System.out.println("true");
}else{
//格式错误
System.out.println("false");
}
}
测试代码如下: public static void main(String[] args) {
String regx = "(he){1,2}+";
String date = "55hehe454*2";
Pattern p2 = Pattern.compile(regx);
Matcher m2 = p2.matcher(date);
if(m2.find()){
//格式正确
System.out.println("true");
}else{
//格式错误
System.out.println("false");
}
}
String regx = "he";
String str = "55herrhe5he4*he2";
System.out.println(temp(str,regx));
str = "he343";
System.out.println(temp(str,regx));
}
private static boolean temp(String str,String regex){
Pattern p2 = Pattern.compile(regex);
Matcher m = p2.matcher(str);
int k = 0;
while(m.find()){
k ++;
if(k == 2)
return false;
}
return true;
}
// str 中只能出现一次 he
boolean b = str.matches("(?s)^(?:(?!he).)*he(?:(?!he).)*$");
输出结果 -- true