有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我试图读取一个文本文件,找到特定的匹配项并打印出来,但我的代码不起作用

我把它放在查找字符串匹配项上,只是成功地显示build,没有其他内容。我把它放在查找字符串匹配项上,只是成功地显示build,没有其他内容。我把它放在查找字符串匹配项上,只是成功地显示build,没有其他内容

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) 个答案

  1. # 1 楼答案

    contains()不是这样工作的

    Contains returns true if and only if this string contains the specified sequence of char values.

    你能做的是:

    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
    }