[英]Java Regular Expression - allow only certain characters and digits
I need to write regular expression that allows only digits, characters like & | 我需要编写正则表达式,只允许数字,像&|这样的字符 .
。 ( ) and spaces.
()和空格。
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
List<String> input = new ArrayList<String>();
input.add("(0.4545 && 0.567) || 456"); // should PASS
input.add("9876-5-4321");
input.add("987-65-4321 (attack)");
input.add("(0.4545 && 0.567) || 456 && (me)");
input.add("0.456 && 0.567"); // should PASS
for (String ssn : input) {
boolean f = ssn.matches("^[\\d\\s()&|.]$");
if (f) {
System.out.println("Found good SSN: " + ssn);
}else {
System.out.println("Nope: " + ssn);
}
}
}
}
None above passed, why? 以上都没有通过,为什么?
You forgot to add +
after character class. 您忘记在字符类后添加
+
。 Without it your regex will only accept one-character strings with characters from your character class. 没有它,您的正则表达式将只接受带有字符类中字符的单字符字符串。 Try with
试试吧
boolean f = ssn.matches("^[\\d\\s()&|.]+$");
Because your regular expression accepts single input only (either digits or characters or symbols you specified) 因为正则表达式只接受单个输入(您指定的数字或字符或符号)
Use ^[\\\\d\\\\s()&|.]*$
for getting multiple times 使用
^[\\\\d\\\\s()&|.]*$
获取多次
'+ 1 or more' '+ 1或更多'
? ? 0 or one
0或1
'* 0 or more' '* 0或更多'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.