简体   繁体   English

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

[英]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.

相关问题 java中特殊字符(除数字和字母之外的所有内容)的正则表达式是什么 - What is the Regular Expression for special characters (everything except digits & alphabets) in java 用于数字和短划线的Java正则表达式 - Java regular expression for digits and dashes 正则表达式 - 允许空格和任意位数 - Regular expression - allow space and any number of digits 我正在寻找一个正则表达式来允许 6 个字符,并且在 6 个字符内,它应该只允许 3 个字母和 3 个数字 - I am looking to write a regular expression to allow 6 characters and within the 6 characters, It should only allow 3 alphabets and 3 numbers 正则表达式使用JavaScript在JSP中仅允许使用0-9位数(甚至不包括&#39;。&#39;[Dot]) - Regular Expression to allow only 0-9 digits only (Not even '.' [Dot]) in JSP using javascript Java - 检查是否以特定字符开头和结尾的正则表达式 - Java - regular expression to check if begins and ends with certain characters Java中的正则表达式仅允许使用字母数字输入数据 - Regular expression in java to allow only alphanumeric input data Java Regex:仅允许某些字符,但不允许某些字符以字符串开头? - Java Regex: Allow only certain characters, but don't allow certain characters to begin the string? 正则表达式只允许 1 个破折号 - regular expression to allow only 1 dash Java:输入字段的正则表达式只有数字和逗号+空格字符 - Java: Regular expression for the input field only numbers and commas + space characters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM