java - 包含字母数字和所有特殊字符(% 除外)的正则表达式

标签 java regex

正则表达式,包含字母数字和所有特殊字符(% 除外)

字符串长度必须为 1 到 12。

尝试这种方式(作为正则表达式),但这也允许 %。

[[^=][\w\S][^-]]{1,13}   

示例我的输入字符串(itemValue)对于上述模式,应该给出 false:test%t1z

            Pattern pattern = Pattern.compile(regexStr);
            Matcher matcher = pattern.matcher(itemValue);

            if(matcher.matches()){
                flag = true;
            }

最佳答案

您可以使用以下任一方法:

String regexStr = "[^%]{1,12}";    # If whitespaces are allowed
String regexStr = "[^%\\s]{1,12}"; # If whitespaces are disallowed

请注意,Pattern#matches 需要完整的字符串匹配,因此无需添加像 \A/\z 这样的 anchor 正则表达式模式。

详细信息

  • [^%]{1,12} - 匹配 % 之外的任何一到十二个字符
  • [^%\s]{1,12} - 匹配除 % 和空格之外的一到十二个字符

请参阅Java demo :

List<String> strs = Arrays.asList("abc123#67812", "abc123%67812", "abc123#678120");
String regexStr = "[^%\\s]{1,12}";
Pattern pattern = Pattern.compile(regexStr);

for (String itemValue : strs) {
    Matcher matcher = pattern.matcher(itemValue);
    System.out.println("\"" + itemValue + "\": " + matcher.matches());
}

// => "abc123#67812": true
//    "abc123%67812": false
//    "abc123#678120": false

关于java - 包含字母数字和所有特殊字符(% 除外)的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67522594/

相关文章:

python - 在自定义 SublimeLinter 插件中突出显示

python re codecs ä ö,芬兰语,定义单词

regex - vim中以**开头的行大写

Java 套接字服务器显示空白窗口

java - 如何在java中将简单的JSONObject转换为HashMap键,值对

java - 如何在用户输入错误(超出范围)值后提示用户输入正确值?

php - 基本正则表达式帮助

c# - 整数或 double 值的正则表达式

Java 处理两个自定义反序列化器

java - 读取 EOF 后使用 Scanner 类读取 Standard.In 时出现 NoSuchElementException