Java String.matches()不匹配

Java String.matches()不匹配,java,Java,条件不匹配 string1 = "k" string2 = "k(1)" String regex = "\\\d+"; if ((string1 +"("+regex+")").matches(string2)) { return true; } 反过来说。它是s.matches(regexp),而不是regexp.matches(s) 您还应该避开圆括号(“(”和“)”),因为它们在正则表达式中有特殊含义。因此,它应该是: string2.matches(Pattern.quote

条件不匹配

string1 = "k"
string2 = "k(1)"
String regex = "\\\d+";
if ((string1 +"("+regex+")").matches(string2)) {
    return true;
}

反过来说。它是
s.matches(regexp)
,而不是
regexp.matches(s)

您还应该避开圆括号(“(”和“)”),因为它们在正则表达式中有特殊含义。因此,它应该是:

string2.matches(Pattern.quote(string1) + "\\(" + regex + "\\)");

你在拖延争论。regex必须传入
matches
方法的参数,并且必须对要分析的字符串调用该方法:

string2.matches(string1 + "(" + regex + ")")
看看这个