Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 验证数字序列_Java_Regex - Fatal编程技术网

Java 验证数字序列

Java 验证数字序列,java,regex,Java,Regex,我正在使用Java,我需要验证这样的数字序列:9999/9999 我尝试使用这个正则表达式\\d{4}\\\\d{4},但是对于匹配(),我得到了false 我的代码: Pattern regex = Pattern.compile("\\d{4}\\\\d{4}"); if (!regex.matcher(mySequence).matches()) { System.out.println("invalid"); } else { S

我正在使用Java,我需要验证这样的数字序列:
9999/9999

我尝试使用这个正则表达式
\\d{4}\\\\d{4}
,但是对于
匹配()
,我得到了
false

我的代码:

    Pattern regex = Pattern.compile("\\d{4}\\\\d{4}");

    if (!regex.matcher(mySequence).matches()) {
        System.out.println("invalid");
    } else {
        System.out.println("valid");
    }

有人能帮我吗?

正则表达式模式试图匹配反斜杠而不是正斜杠字符。您需要使用:

Pattern regex = Pattern.compile("\\d{4}/\\d{4}")
应该是

Pattern regex = Pattern.compile("\\d{4}/\\d{4}");
Pattern regex = Pattern.compile("\\d{4}/\\d{4}");

将您的模式更改为:

Pattern regex = Pattern.compile("\\d{4}\\\\\\d{4}");
用于匹配
“9999\\9999”
(实际值:9999\9999)(在java中,在声明
字符串时需要转义)

或者,如果要匹配
“9999/9999”
,则上述解决方案可以正常工作:

Pattern regex = Pattern.compile("\\d{4}/\\d{4}");