部分字符串匹配

时间:2017-02-10 15:05:21

标签: java string

我正在比较两个不同地图的两个值,并寻找精确匹配和部分匹配。我正在使用val1.contains(val2)检查部分匹配,但获得false。我匹配的字符串示例是:

val1: Kansas City Athletics  
val2: Athletics

为什么contains()方法在这种情况下不起作用?

编辑

如果我的价值观互换,这应该仍然有效吗?例如。如果

val1: Kansas City Athletics

val2: Athletics

这是我的代码:我正在迭代两个地图的值并比较值以获得精确匹配和部分匹配。

List<Integer> compareResults = new ArrayList<Integer>();
int i_index = 0;
for (Entry<String, Vector<String>> entry : annotationMap.entrySet()) {///String key: annotationMap.keySet()){
  for (Entry<String, Vector<String>> rageEntry : rageMap.entrySet()) {
   if (entry.getKey().equals("ORGANIZATION")) {
    for (String val : entry.getValue()) {
        recusion:
        for (int i = i_index; i <= rageEntry.getValue().size(); ) {
            String rageVal = rageEntry.getValue().elementAt(i);
            if (val.equals(rageVal)) {
                orgTruePositiveCount++;
                i_index++;
                break recusion;
            } else if (val.contains(rageVal)) {  //|| dataB.get(entryA.getKey()).contains(entryA
                // .getValue())){
                orgTruePositiveCount++;
                i_index++;
                break recusion;
            } else if (!val.contains(rageVal)) {
                orgFalseNegativeCount++;
                i_index++;
                break recusion;
            } else if (!rageVal.contains(val)) {
                orgFalsePositiveCount++;
                i_index++;
                break recusion;
            }

        }
    }
}

if (entry.getKey().equals("PERSON")) {
    for (String val : entry.getValue()) {
        recusion:
        for (int i = i_index; i <= rageEntry.getValue().size(); ) {
            String rageVal = rageEntry.getValue().elementAt(i);

            if (val.equals(rageVal)) {
                perTruePositiveCount++;
                i_index++;
                break recusion;
            } else if (val.contains(rageVal)) {
                perTruePositiveCount++;
                i_index++;
                break recusion;
            } else if (!val.contains(rageVal)) {
                perFalseNegativeCount++;
                i_index++;
                break recusion;
            } else if (!rageVal.contains(val)) {
                perFalsePositiveCount++;
                i_index++;
                break recusion;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

它似乎适用于您描述的情况 - 请参阅此简单示例:

public class ContainsExample {
  public static void main(final String[] args) {
    final String val1 = "Kansas City Athletics";
    final String val2 = "Athletics";
    System.out.println(val1.contains(val2));
    System.out.println(val2.contains(val1));
  }
}

运行此产生:

$ java ContainsExample
true
false