-1

我在下面有三个字符串 a、b、c,我试图让字符串 exp 与字符串 b 部分匹配,但是每次运行代码时都没有匹配。

  String a = "ID = '5' && name='abc' || level='5'";
  String b = "ID = '6' && name='def' || level='6' && year='2012'";
  String exp = "ID = '6' && name='def' || level='6'";

我的代码:

  Pattern p = Pattern.compile(b);
  Matcher m = p.matcher(exp);
  if(m.matches()){
        System.out.println("Perfect Match");
  }
  else if(m.hitEnd()){
        System.out.println("Partial Match");
  }
  else{
        System.out.println("No Match");
  }

即使我删除了 && year='2012',它也没有给我匹配。

4

2 回答 2

1

You shouldn't be compiling b into a Pattern, you should be compiling exp. This will allow you to search through b for exp.

The way you have it now searches for b within exp, which will never find a match since exp is a subset of b.

于 2012-06-15T17:08:24.740 回答
0

如果您只想要部分匹配,那么您不需要正则表达式。

用这个:

if (b.contains(exp))

要检查两个字符串是否相等,您可以使用:

if (b.contentEquals(exp))

于 2012-06-15T16:59:49.053 回答