簡體   English   中英

我正在嘗試讀取文本文件並查找特定匹配項並打印它,但我的代碼不起作用

[英]I'm trying to read a text file and find specific matches and print it , but my code does not working

我把這個用來查找字符串匹配,只顯示構建成功沒有別的。我把這個用來查找字符串匹配,只顯示構建成功沒有別的。我把這個用來查找字符串匹配,只顯示構建成功沒有別的.

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();
        }
    }     
}

contains() 不是這樣工作的。

當且僅當此字符串包含指定的字符值序列時,包含返回 true。

你可以做的是:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM