有 Java 编程相关的问题?

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

字符串Java正则表达式模式匹配以

我有一个包含很多行的文件。 我想找到一个以“msql”开头的特定行

我试过很多正则表达式组合,但都不知道

Pattern pattern = Pattern.compile("^msql");
Matcher matcher = pattern.matcher(s);

或者

s.matches("^(msql).*$")  or s.matches("^msql")

请建议找到以“msql”开头的行的正确正则表达式

编辑:-

我有这样的文件数据:-

eventlogger 0 0 1 1 1 10
expireserv 0 0 1 1 1 10 "
partEOLserv 0 0 1 1 1 10
msqlpdmm81dd 0 0 25 25 25

还有我的密码

String s = br.readLine();
while (s != null) {
    //Pattern pattern = Pattern.compile("^msql");
    //("^(msql).*$")
    //Matcher matcher = pattern.matcher(s);
    System.out.println(s);

    if (s.startsWith("msql")) {
        System.out.println(s);

    }

    s = br.readLine();
}

我还是找不到线


共 (2) 个答案

  1. # 1 楼答案

    与内容匹配的正则表达式是正确的。我不知道你为什么要面对这个问题。我已经试过你的程序,它正在运行
    我在下面用regex添加代码

    BufferedReader br = new BufferedReader(new FileReader("<filepath\\filename.extension>"));
            String s;
            while ((s = br.readLine()) != null) {
                if (s.matches("^(msql).*$")){
                    System.out.println(s);
                } else {
                    System.out.println("didnt matched");
                }
            }
    

    您也可以使用

    if (s.startsWith("msql"))
    

    这也很有效
    我已经在本地创建了一个文本文件,并将您的数据保存在其中。我得到以下输出

    didnt matched
    didnt matched
    didnt matched
    msqlpdmm81dd 0 0 25 25 25
    

    我觉得这应该管用

  2. # 2 楼答案

    我认为你只读了第一行,因此没有找到匹配项

      public static void main(String[] args) throws Exception {
            File f = new File("example.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            String temp = null;
            while ((temp=br.readLine())!=null) {
                if (temp.startsWith("msql")){
                    System.out.println("Match found: "+temp);
                }
            }
        } 
    

    输出为Match found: msqlpdmm81dd 0 0 25 25 25