Java正则表达式-仅允许某些字符和数字
我需要编写只允许数字、字符(如&|)的正则表达式。()和空格Java正则表达式-仅允许某些字符和数字,java,regex,Java,Regex,我需要编写只允许数字、字符(如&|)的正则表达式。()和空格 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
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);
}
}
}
}
import java.util.*;
导入java.lang.*;
导入java.io.*;
/*只有当类是公共的时,类的名称才必须是“Main”*/
表意文字
{
公共静态void main(字符串[]args)引发java.lang.Exception
{
列表输入=新的ArrayList();
input.add(((0.4545&&0.567)| | 456);//应该通过
输入。添加(“9876-5-4321”);
输入。添加(“987-65-4321(攻击)”;
输入。添加(“(0.4545和0.567)| | 456和(me)”;
input.add(“0.456&&0.567”);//应该通过
for(字符串ssn:输入){
布尔f=ssn.matches(“^[\\d\\s()&.]$”;
如果(f){
System.out.println(“发现良好SSN:+SSN”);
}否则{
系统输出打印项次(“否:+ssn”);
}
}
}
}
上面没有通过,为什么?您忘记在字符类之后添加
+
。如果没有它,正则表达式将只接受一个包含字符类中字符的字符串。试一试
boolean f = ssn.matches("^[\\d\\s()&|.]+$");
因为正则表达式只接受单个输入(指定的数字、字符或符号) 使用
^[\\d\\s()&|.]*$
获取多次
“+1或更多”
??0或1
“*0或更多”搜索其中一个在线正则表达式检查器,并确认正则表达式的功能与您认为的一样。。。