如何在java中找到相应的字符串模式集?

时间:2012-10-31 11:25:01

标签: java

我有一个字符串

             "yes 12 /12 /yes /n
              yes 12 /12 /yes "

如果字符串中有“是”,我怎么检查,我有一个相应的“/ yes”,同样,每当我有“12”时,我都有一个相应的“/ 12”? 例如,如果字符串为

             "yes 12 /12 /yes /n 
              yes 12 /12 "

它应该在第2行给出错误说错误,然后继续读取文件的其余部分。

4 个答案:

答案 0 :(得分:0)

使用String.contains()方法

String s= "yes 12 /12 /yes /n"
if(s.contains("yes") && s.contains("/yes")){
   sysout("yes");
}

对任何其他一对做同样的事情:)

答案 1 :(得分:0)

首先,您需要获取所有单词的列表。然后对于每个单词,尝试查看是否包含/ word。

String s = "12 a /12";
List<String> list = Arrays.asList(s.split("\\s"));
for (String value : list) {
  if (list.contains("/" + value)) {
    System.out.println("Does contain");
  } else {
    System.out.println("Doesn't contain");
  }
}

答案 2 :(得分:0)

您可以在contains课程中使用String方法:

String str = ""yes 12 /12 /yes /n";
boolean isOk = str.contains("yes") && str.contains("/yes"); // isOk = true

str = "yes 12 /12 ";
isOk = str.contains("12") && str.contains("/12") // isOk = false

答案 3 :(得分:0)

您可以使用一些递归来查找标记和相应的结束标记:

public class TagMatching {
    public static void main(String[] args) {
        List<String> lines = Arrays.asList("yes 12 /12 /yes /n",
                                           "yes 12 /12 /yes",
                                           "yes 12 a b /12 /yes",
                                           "yes 12 c /12 /yes");
        for (String line : lines) {
            boolean valid = validate(Arrays.asList(line.split(" ")));
            System.out.println("valid = " + valid);
        }
    }

    public static boolean validate(List<String> tags) {
        if (tags.size() == 0) {
            return true;
        }

        String first = tags.get(0);
        String last = tags.get(tags.size() - 1);
        if (last.equals("/" + first)) {
            return validate(tags.subList(1, tags.size()-1));
        }

        return false;
    }
}