简体   繁体   English

对Java正则表达式感到困惑

[英]Confused about Java Regular Expressions

What I'm trying to do is look from a list of files in a directory and see which file name has the pattern 'output'. 我想做的是从目录中的文件列表中查找,并查看哪个文件名具有模式“输出”。 If the file does contain the word 'output' then I just want to print it to screen. 如果文件确实包含“输出”一词,那么我只想将其打印到屏幕上。 That's it. 而已。

Here is my code that doesn't work. 这是我的代码不起作用。 Why doesn't it work? 为什么不起作用?

package duplicate_search;

import java.io.File;
import java.util.regex.*;
import java.util.Scanner;

public class Search {
public static void main(String [] args){
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter the directory to search: ");
    String dir = keyboard.next();

    Pattern p = Pattern.compile("output");
    Matcher m = null;
    System.out.println
              ("Now search for *." + p + " files.");
    File folder = new File(dir);
    File[] listOfFiles = folder.listFiles();


    for(File f : listOfFiles){
        m = p.matcher(f.getName());
        if(m.matches()){
            System.out.println(f.getName());
        }
      }
    }
}

If you want to match filenames that contain "output", then you don't want to use matches , but instead, find . 如果要匹配包含“输出”的文件名,则不要使用matches ,而是使用find

From the docs: 从文档:

The matches method attempts to match the entire input sequence against the pattern. matchs方法尝试将整个输入序列与模式进行匹配。

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Matcher.html http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Matcher.html

.matches() does a full match. .matches()进行完全匹配。 check for .*output.* or use find() 检查.*output.*或使用find()

Why aren't you using contains() method? 为什么不使用contains()方法? Unless I'm not getting your question right you can check if a string contains that character sequence: 除非我没有正确回答您的问题,否则您可以检查字符串是否包含该字符序列:

f.getName().contains("output"); //Returns true if the string contains "output"

IMHO a regular expression seems like an overkill here, unless you have your reasons of course. 恕我直言,除非您有充分的理由,否则在这里使用正则表达式似乎是过大的选择。

Here is the modified code, 这是修改后的代码,

import java.io.File;
import java.util.regex.*;
import java.util.Scanner;

public class Search {
public static void main(String [] args){
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter the directory to search: ");
    String dir = keyboard.next();

    Pattern p = Pattern.compile("output");
    Matcher m = null;
    System.out.println
              ("Now search for *." + p + " files.");
    File folder = new File(dir);
    File[] listOfFiles = folder.listFiles();


    for(File f : listOfFiles){
        m = p.matcher(f.getName());
        if(m.find()){ // change to find instead of m.matches()
            System.out.println(m.group()); // return the string sequence which is matched
        }
      }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM