允许特定特殊字符的正则表达式

Regular Expression to allow specific special characters

我目前正在验证用户名输入,我必须验证允许将某些特殊字符插入到输入中。

字符的白名单是:

$#+{}:?.,~@" 和空格

列入黑名单的角色是:

^$;\-()<>|='%_

验证应允许带有一个或多个特殊字符和空格的任何字母数字字符。它也可以与黑名单案例一起工作。

我有这个:

public static boolean alphNum(String value) {
    Pattern p = Pattern.compile("^[\w ]*[^\W_][\w ]*$");
    Matcher m = p.matcher(value);
    return m.matches();
}

仅适用于字母数字字符和空格,但现在还希望允许特定的特殊字符列表。

以下是我需要允许的类型的一些示例:

我看过很多正则表达式验证,但是 none 这个很具体,如果有人能帮我解决这个问题,我将不胜感激。

如果没有 "must start with a letter" 或 "must contain at least one letter" 等限制(您的问题未指定任何限制),并假设 "white spaces" 是指 space , 但不是制表符、换行符等,则表达式将只是:

Pattern.compile("^[\$#\+{}:\?\.,~@\"a-zA-Z0-9 ]+$");

请注意,此正则表达式允许诸如仅单个 space 或与另一个相同的用户名(但尾随 space 的数量除外)等内容,如果您想要多一点限制并强制以字母或数字开头(例如),你可以这样做:

Pattern.compile("^[a-zA-Z0-9][\$#\+{}:\?\.,~@\"a-zA-Z0-9 ]+$");

使用此模式允许不在您的黑名单字符上的字符。

"[^^;\-()<>|='%_]+"

第一个^表示不是以下任何字符。在你澄清 $ 是好是坏之前,我将其视为一个好角色。

代码示例:

public static void main(String[] args) throws Exception {
    List<String> userNames = new ArrayList() {{
        add("Name1$");          // Good
        add("Name1# Name2");    // Good
        add("Name1 Name2");     // Good
        add("Name Name2");      // Good
        add("Name1 Name");      // Good
        add("UserName$");       // Good
        add("UserName^");       // Bad
        add("UserName;");       // Bad
        add("User-Name");       // Bad
        add("User_Name");       // Bad
    }};
    Pattern pattern = Pattern.compile("[^^;\-()<>|='%_]+");

    for (String userName : userNames) {
        if (pattern.matcher(userName).matches()) {
            System.out.println("Good Username");
        } else {
            System.out.println("Bad Username");
        }
    }
}

结果:

Good Username
Good Username
Good Username
Good Username
Good Username
Good Username
Bad Username
Bad Username
Bad Username
Bad Username
public class Patteren {
       private static final Pattern specialChars_File = Pattern.compile("[a-zA-Z0-9-/.,:+\s]*");

     //CASE-1 : Allow only charaters specifed, here im aloowiing ~ '
      private static final Pattern specialCharsRegex_Name = Pattern.compile("[a-zA-Z0-9~']*");

      //.CASE-2: Dont Allow specifed charaters, here im not aloowiing < >
      private static final Pattern specialCharRegex_Script = Pattern.compile("[<>]");

 public static void main(String[] args) {

     if (!specialCharsRegex_Name.matcher("Satya~").matches()) {
       System.out.println("InValid....Error message here ");
     }

     if (specialCharRegex_Script.matcher("a").find()) {
       System.out.println("SCript Tag ... Error Message");
     }
   }
 }