Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was trying out to create a regular expression to match file path in java like

C:abcdefghiabc.txt

I tried this ([a-zA-Z]:)?(\[a-zA-Z0-9_-]+)+\? , like following code

import java.util.regex.Pattern;

  public class RETester {

public static void main(String arhs[]){

    String regularExpression = "([a-zA-Z]:)?(\[a-zA-Z0-9_-]+)+\?";

    String path = "D:\directoryname\testing\abc.txt";

    Pattern pattern = Pattern.compile(regularExpression);

    boolean isMatched = Pattern.matches(regularExpression,path);
    System.out.println(path);
    System.out.println(pattern.pattern());
    System.out.println(isMatched);

}

}

However it's always giving me , false as result . Pls help me .

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
666 views
Welcome To Ask or Share your Answers For Others

1 Answer

Java is using backslash-escaping too, you know, so you need to escape your backslashes twice, once for the Java string, and once for the regexp.

"([a-zA-Z]:)?(\\[a-zA-Z0-9_.-]+)+\\?"

Your regexp matched a literal '[-zA-Z0-9_-' string, and a literal '?' at the end. I also added a period in there to allow 'abc.txt'..

That said, consider using another mechanism for determine valid file names, as there are different schemes (i.e. unix). java.util.File will probably throw an exception if the path is invalid, which might be a good alternative, although I don't like using exceptions for control flow...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...