0

Possible Duplicate:
C# - Regex for file paths e.g. C:\test\test.exe

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

Like C:/WINDOWS/Profiles/myComputer/Desktop/test.xml

Pls help me.

Thank you very much

Community
  • 1
  • 1
hamada karim
  • 29
  • 1
  • 3
  • 2
    Do you need a regular expression? Moreover, this is going to give you trouble - the characters allowed are system-dependent; notably, there's File.separator, and some systems allow :, others do not. – ignis Oct 31 '12 at 14:05
  • @see [File.exists()](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#exists()). – ignis Oct 31 '12 at 14:15

3 Answers3

1

you could try this,

 (?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+\.(?i)(txt|xml|gif|pdf|doc|docx|xls|xlsx)$

Explanation:

^(?:[\w]\:|\\) -- Begin with x:\ or \\
[a-z_\-\s0-9\.] -- valid characters are a-z| 0-9|-|.|_ (you can add more)
(?i) -- regular expression case-insensitive
(txt|xml|gif|pdf|doc|docx|xls|xlsx) -- Valid extension (you can add more)
Sasi Kathimanda
  • 1,788
  • 3
  • 25
  • 47
0

you could use something like this

"([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-]+)+\\\\?"
Zaki
  • 6,997
  • 6
  • 37
  • 53
Bahram
  • 1,464
  • 2
  • 22
  • 38
0
Matcher ma = Pattern.compile("([a-zA-Z]:(?:/[\\w\\s]+)*/[\\w\\s]+\\.\\w+)")
                .matcher("C:/WINDOWS/Profiles/myComputer/Desktop/test.xml");
while (ma.find()) {
    System.out.println(ma.group(1));
}

Here's an example working for your case. maybe you need to add some characters that aren't allowed but it's just adding chars in [\w\s.] <- that would accept dots too.

Javier Diaz
  • 1,791
  • 1
  • 17
  • 25