簡體   English   中英

Java正則表達式-僅允許某些字符和數字

[英]Java Regular Expression - allow only certain characters and digits

我需要編寫正則表達式,只允許數字,像&|這樣的字符 ()和空格。

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

以上都沒有通過,為什么?

您忘記在字符類后添加+ 沒有它,您的正則表達式將只接受帶有字符類中字符的單字符字符串。 試試吧

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

因為正則表達式只接受單個輸入(您指定的數字或字符或符號)

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

'+ 1或更多'

0或1

'* 0或更多'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM