[英]Regular expression in java to allow only alphanumeric input data
I need the regex expression which would accept only alphanumeric data. 我需要只接受字母数字数据的正则表达式。
Say for eg: ABC12DG - should allow this 例如:ABC12DG-应该允许
if input data is 123000 - should not allow as it is only numeric. 如果输入数据为123000,则不允许输入,因为它只能是数字。
I have tried this 我已经试过了
say a is a string which contains the input data 说a是包含输入数据的字符串
then a.matches("^[a-zA-Z0-9]+$") this allows both the first and second input as above 然后a.matches(“ ^ [a-zA-Z0-9] + $”)这样就可以同时进行第一个和第二个输入
I only want it to allow the alphanumeric input , not just numeric or alphabets How to do that 我只希望它允许字母数字输入,而不仅仅是数字或字母。
Use negative lookahead or alternation operator. 使用负前瞻或交替运算符。
a.matches("^(?![A-Za-z]+$)(?!\\d+$)[a-zA-Z0-9]+$");
(?![A-Za-z]+$)
asserts that the match won't contain only alphabets. (?![A-Za-z]+$)
断言该匹配项不会仅包含字母。 (?!\\\\d+$)
asserts that the match won't contain only digits. (?!\\\\d+$)
断言匹配将不只包含数字。 [a-zA-Z0-9]+
Matches one or more alphanumeric characters. [a-zA-Z0-9]+
匹配一个或多个字母数字字符。 or 要么
a.matches("^[a-zA-Z0-9]*(?:[a-zA-Z]\\d|\\d[a-zA-Z])[a-zA-Z0-9]*$");
You can try this Regex for your text: 您可以为文本尝试以下正则表达式:
String reg = "\\p{Alpha}+\\d+";
String str1 = "It &* is %$ now OK 2015";
String str2 = "ItisnowOK2015";
String str3 = "888";
String str4 = "aaa";
System.out.println("str1 = "+str1.matches(reg));
System.out.println("str2 = "+str2.matches(reg));
System.out.println("str3 = "+str3.matches(reg));
System.out.println("str4 = "+str4.matches(reg));
And is the result: 结果是:
str1 = false
str2 = true
str3 = false
str4 = false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.