Java正则表达式 - 仅允许某些字符和数字

时间:2014-01-17 05:37:33

标签: 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
    {

        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);
            }
        }
    }
}

以上没有通过,为什么?

2 个答案:

答案 0 :(得分:5)

你忘了在角色课后添加+。如果没有它,你的正则表达式只接受带有你角色类字符的单字符字符串。试试

boolean f = ssn.matches("^[\\d\\s()&|.]+$");

答案 1 :(得分:2)

因为您的正则表达式只接受单个输入(您指定的数字或字符或符号)

使用^[\\d\\s()&|.]*$获取多次

'+ 1或更多'

? 0或一个

'* 0或更多'

相关问题