![](/img/trans.png)
[英]How to extract the first letter and the following three digits from a string using regex java
[英]Java regex: First three digits are not 666
我需要创建一个正则表达式,如果前三位数不是666,则返回true。以下是一些示例:
66600abc - 假
606asdfnh - 是的
600asdfasdf -true
我试过这个,但是我得不到想要的结果。
System.out.println(Pattern.matches("[(^[(6)(6)(6)])][a-zA-Z0-9]*", "6660"));
System.out.println(Pattern.matches("[^6]{3}[a-zA-Z0-9]*", "606"));
System.out.println(Pattern.matches("[^666]{3}[a-zA-Z0-9]*", "506"));
System.out.println(Pattern.matches("[^666][a-zA-Z0-9]*", "636"));
System.out.println(Pattern.matches("[^666][a-zA-Z0-9]*", "666"));
使用否定前瞻(?!666)
并匹配字母数字符号,您可以使用\\p{Alnum}
:
System.out.println("6660".matches("(?!666)\\p{Alnum}*"));
请注意, matches()
默认锚定模式,不需要^
和$
。
一些在线测试 :
System.out.println("6660".matches("(?!666)\\p{Alnum}*")); // false
System.out.println("66600abc".matches("(?!666)\\p{Alnum}*")); // false
System.out.println("606asdfnh".matches("(?!666)\\p{Alnum}*")); // true
System.out.println("600asdfasdf".matches("(?!666)\\p{Alnum}*")); // true
更新 :
由于这是JFlex, 如果最小字符数为3且 仅允许使用字母数字符号,则可以使用此正则表达式:
"^([a-zA-Z0-9]{1,2}$|[a-zA-Z0-57-9][a-zA-Z0-9]{2}|[a-zA-Z0-9][a-zA-Z0-57-9][a-zA-Z0-9]|[a-zA-Z0-9]{2}[a-zA-Z0-57-9])[a-zA-Z0-9]*"
如果您需要允许任何字符,而不仅仅是字母数字,您可以使用替换[a-zA-Z0-9]
.
[a-zA-Z0-57-9]
与[^6]
:
"^(.{1,2}$|[^6].{2}|.[^6].|.{2}[^6]).*"
请参阅正则表达式演示
请注意,您可能会在我以前的正则表达式中找到类似的模式:匹配除了 SO答案之外的所有内容 。
不要仅使用Pattern.matches来检查魔术值。
如果您希望您的字符串不以“666”开头,请使用String.startWith(String)进行检查:
class Test {
public static Boolean isNotEvil(String str) {
return !myString.startWith("666");
}
public static void main(String [] args)
{
System.out.println(Test.isNotEvil("azerty") ? "Not evil" : "Evil!" );
System.out.println(Test.isNotEvil("66600abc") ? "Not evil" : "Evil!" );
System.out.println(Test.isNotEvil("606asdfnh") ? "Not evil" : "Evil!" );
System.out.println(Test.isNotEvil("600asdfasdf") ? "Not evil" : "Evil!" );
System.out.println(Test.isNotEvil("666") ? "Not evil" : "Evil!" );
}
}
结果:
Not evil
Evil!
Not evil
Not evil
Evil!
你可以尝试这个:
([^6]|.[^6]|..[^6]).*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.