繁体   English   中英

正则表达式部分检查,使用find方法返回false

[英]partial regex checking return false on using find method

我有一个输入000.100.112,它给下面的代码输入错误,我只需要部分检查是否存在,返回true部分检查正在工作

     String emailRegex="/^(000\\.000\\.|000\\.100\\.1|000\\.[36])/";
    Pattern thePattern = Pattern.compile(emailRegex);
    Matcher m = thePattern.matcher(data);
    if (m.matches()) {
        return true;
    }
    return m.find();

我希望部分检查为true,但它为false 在此处输入图片说明 它在此在线正则表达式检查中提供了匹配项

Java正则表达式模式不使用斜杠定界符,就像在其他语言(例如PHP)中那样。 另外,由于需要部分匹配,因此应使用以下模式:

^(000\.000\.|000\.100\.1|000\.[36]).*
                                  ^^^^ necessary

请仔细注意模式末尾的.* ,否则部分匹配将不起作用。

String emailRegex="^(000\\.000\\.|000\\.100\\.1|000\\.[36]).*";
Pattern thePattern = Pattern.compile(emailRegex);
Matcher m = thePattern.matcher("000.100.112");
if (m.matches()) {
    System.out.println("MATCH");
}

编辑:

正如@MarkMobius指出的那样,您还可以将原始模式与Matcher#find()

String emailRegex="^(000\\.000\\.|000\\.100\\.1|000\\.[36])";
Pattern thePattern = Pattern.compile(emailRegex);
Matcher m = thePattern.matcher("000.100.112");
if (m.find()) {
    System.out.println("MATCH");
}

您的在线正则表达式测试仪使用JavaScript正则表达式文字。 在JavaScript中,正则表达式可以用/.../分隔。 您在在线正则表达式测试器中看到的开头和结尾的/实际上并不是正则表达式模式的一部分。 它们就像Java字符串中的引号。

"string"的引号不是字符串的一部分。 同样, /someregex/的斜杠也不是正则表达式的一部分。

因此,在Java中使用正则表达式时,不应包括这些斜杠:

String emailRegex="^(000\\.000\\.|000\\.100\\.1|000\\.[36])";

如果这样做,它们将被解释为好像您要在字面上匹配斜杠。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM