简体   繁体   English

验证文本的正则表达式,其中包含某些特殊字符

[英]Regular expression of validating text which contains certain special characters on condition

I am trying to create a regular expression which will validate a text. 我正在尝试创建一个将验证文本的正则表达式。 Conditions are as follows: 条件如下:

  1. Must contain at least one alphanumeric character [A-Za-z0-9] 必须至少包含一个字母数字字符[A-Za-z0-9]

  2. Can contain allowed special character like [@#]. 可以包含允许的特殊字符,例如[@#]。 This is optional. 这是可选的。

  3. No other characters are allowed other than the above mentioned chars[includes @ and #]. 除上述字符[包括@和#]外,不允许其他字符。
  4. Text length should be less than 8. 文字长度应小于8。

valid text: A, A@, @A, A@a@, @@@a etc 有效文本: A,A @,@ A,A @ a @,@@@ a等

invalid text : @, @#, a:**, A@%, AAAAAAAAA(9 characters) etc 无效文字: @,@#,a:**,A @%,AAAAAAAAA(9个字符)等

I have tried the below regex but it is partly working: 我尝试了以下正则表达式,但部分起作用:

(?=. [\\w])(?=. [@#])?.*{0,8} (?=。 [\\ w])(?=。 [@#])?。* {0,8}

^(?=.*[a-zA-Z0-9])[A-Za-z0-9@#]{0,8}$

Try this.See demo. 试试看。看演示。

The lookahead will make sure there is atleast one character. lookahead将确保至少有one字符。

Use the below regex in matches method. matches方法中使用以下正则表达式。

"(?=.*?[A-Za-z0-9])[A-Za-z0-9@#]{1,8}"

(?=.*?[A-Za-z0-9]) asserts that the string must contain atleast one letter or digit , so there must be a single character present in the match. (?=.*?[A-Za-z0-9])断言字符串必须包含至少一个字母或数字,因此匹配项中必须存在单个字符。 That's why i defined [A-Za-z0-9@#]{1,8} instead of [A-Za-z0-9@#]{0,8} 这就是为什么我定义[A-Za-z0-9@#]{1,8}而不是[A-Za-z0-9@#]{0,8}

String[] check = {"A", "A@", "@A", "A@a@", "@@@a", "@", "@#", "a:**", "A@%", "AAAAAAAAA"};
for(String i: check)
{

    System.out.println(i.matches("(?=.*?[A-Za-z0-9])[A-Za-z0-9@#]{1,8}"));
}

Output: 输出:

true
true
true
true
true
false
false
false
false
false

您可以使用:

^(?=.*?[A-Za-z0-9])[@#A-Za-z0-9]{1,8}$

You can try regex like this : 您可以尝试这样的正则表达式:

public static void main(String[] args) {
    String s = "aaaaaaa";
    System.out.println(s.matches("(?=.*[A-Za-z0-9])[A-Za-z0-9@#]{1,7}"));
}

O/P : true O / P:是

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM