【问题标题】:Regular expression that accepts only characters, numbers and special characters not [duplicate]只接受字符、数字和特殊字符的正则表达式,而不是 [重复]
【发布时间】:2014-08-26 18:07:22
【问题描述】:

我想要一个接受输入字符(A..Z 或 a..z)但不接受数字和特殊字符的正则表达式。 我写了这个方法和这些模式,但它不起作用:

 public static Pattern patternString = Pattern.compile("\\D*");
 public static Pattern special = Pattern.compile("[!@#$%&*,.()_+=|<>?{}\\[\\]~-]");

 public static boolean checkString(String input) {
    boolean bool_string = patternString.matcher(input).matches(); 
    boolean bool_special = !special.matcher(input).matches(); 
    return (bool_string && bool_special);
 }
如果输入为:hellotableFireBlaKc

checkString 应该返回 true,等等。

如果输入为

checkString 应返回 false:10tabl_e+hel/lo

我该怎么做?谢谢

【问题讨论】:

标签: java regex


【解决方案1】:

使用这样的东西:

if (subjectString.matches("[a-zA-Z]+")) {
    // It matched!
  } 
else {  // nah, it didn't match...  
     } 
  • 无需使用^$ 锚定正则表达式,因为matches 方法只查找完整匹配项
  • [a-zA-Z] 是匹配a-zA-Z 范围内的一个字符的字符类
  • + 量词使引擎匹配一次或多次

【讨论】:

  • 谢谢,很高兴它有帮助。 :)
猜你喜欢
  • 2020-07-26
  • 1970-01-01
  • 1970-01-01
  • 2013-11-11
  • 1970-01-01
  • 2011-10-09
  • 1970-01-01
相关资源
最近更新 更多