简体   繁体   中英

Java regex and matcher

What i have did:

public static String cvtPattern(String str) {
    StringBuilder pat = new StringBuilder();
    int start, length;

    pat.append('^');
    if (str.charAt(0) == '\'') {    // double quoting on Windows
        start = 1;
        length = str.length() - 1;
    } else {
        start = 0;
        length = str.length();
    }
    for (int i = start; i < length; i++) {
        switch(str.charAt(i)) {
        case '*': pat.append('.'); pat.append('*'); break;
        case '.': pat.append('\\'); pat.append('.'); break;
        case '?': pat.append('.'); break;
        default:  pat.append(str.charAt(i)); break;
        }
    }
    pat.append('$');
    return new String(pat);
}

Then at my main:

//my args[0] is the string ".java"
pattern = Regex.cvtPattern(args[0]);
Pattern p = Pattern.compile(pattern);
System.out.println("Pattern: " +p.toString());
Matcher m = p.matcher(fileName);
if (m.matches()){
System.out.println("File to be added: "+currentFile.getName());
matchQueue.add(file);
            }

my input is .java and it will be compiled to ^.java$. How come when my file name is anything.java, it doesnt match? Where did i do wrong?

Your pattern is wrong. ^.java$ will not match anthing.java .You need to quantify . to accept more.Your formation should be

^.*\.java$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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