我试图阅读文本文件并查找特定匹配并打印它,但我的代码无法正常工作

时间:2017-09-25 07:31:00

标签: java

我已经把它用于查找字符串匹配,只是显示构建成功没有别的。我已经把它用于查找字符串匹配,只是显示构建成功没有别的。我已经把它找到了字符串匹配,只显示构建成功。

public class Lab1 {
    public static final String FileName = "E:\\test\\new.txt";
    public static void main(String[] args) {

        BufferedReader br = null;
        FileReader fr = null;
        try {
            fr = new FileReader(FileName);
            br = new BufferedReader(fr);

            String r = null;
            r = br.readLine();

            String key = "int, float, if, else , double";
            String iden = "a, b, c, d, e , x , y , z";
            String mat = "int, float, if, else , double";
            String logi = "int, float, if, else , double";
            String oth = "int, float, if, else , double";


            if(r.contains(key)) {
                System.out.println(key.matches(r));
            }

        } catch (IOException e) {
             e.printStackTrace();
        }
    }     
}

1 个答案:

答案 0 :(得分:0)

包含()并不像那样工作。

  

当且仅当此字符串包含时,才返回true   指定的char值序列。

你能做的是:

String key = "(int|float|if|else|double)"; // is a regex to check if one of the words exist
Pattern pattern = Pattern.compile(key);
Matcher matcher = pattern.matcher(r);
while (matcher.find()) { // Checks if the matcher matches r.
  System.out.println(matcher.group()); // return all the words which matched
}

您不必为此使用正则表达式,只需执行以下操作:

List<String> keys = Arrays.asList("int", "float", "if", "else", "double");

Optional<String> possibleMatch = keys.stream()
    .filter(a::contains) // if a contains one of the keys return true
    .findFirst(); // find the first match 

if (possibleMatch.isPresent()) { // if a match is present
  System.out.println(possibleMatch.get()); // print the match
}