简体   繁体   中英

Java regex for Windows file path

I'm trying to build a Java regex to search a .txt file for a Windows formatted file path, however, due to the file path containing literal backslashes, my regex is failing.

The .txt file contains the line:

C\Windows\SysWOW64\ntdll.dll

However, some of the filenames in the text file are formatted like this:

C\Windows\SysWOW64\ntdll.dll (some developer stuff here...)

So I'm unable to use String.equals

To match this line, I'm using the regex:

filename = "C\\Windows\\SysWOW64\\ntdll.dll"
read = BufferedReader.readLine();

if (Pattern.compile(Pattern.quote(filename), Pattern.CASE_INSENSITIVE).matcher(read).find()) {

I've tried escaping the literal backslashes, using the replace method, ie:

filename.replace("\\", "\\\\");

However, this is failing to find, I'm guessing this is because I need to further escape the backslashes after the Pattern has been built, I'm thinking I might need to escape upto an additional four backslashes, ie:

Pattern.replaceAll("\\\\", "\\\\\\\\");

However, each time I try, the pattern doesn't get matched. I'm certain it's a problem with the backslashes, but I'm not sure where to do the replacement, or if there's a better way of building the pattern.

I think the problem is further being compounded as the replaceAll method also uses a regex, with means the pattern will have it's own backslashes in there, to deal with the case insensitivity.

Any input or advice would be appreciated.

Thanks

Seems like you're attempting to to a direct comparison of String against another. For exact matches, you could do (

if (read.equalsIgnoreCase(filename)) {

of simply

if (read.startsWith(filename)) {

Try this :

While reading each line from the file, replace '\\' by '\\\\'.

Then :

String lLine = "C\\Windows\\SysWOW64\\ntdll.dll";
Pattern lPattern = Pattern.compile("C\\\\Windows\\\\SysWOW64\\\\ntdll\\.dll");
Matcher lMatcher = lPattern.matcher(lLine);
if(lMatcher.find()) {
    System.out.println(lMatcher.group());
}

lLine = "C\\Windows\\SysWOW64\\ntdll.dll (some developer stuff here...)";
lMatcher = lPattern.matcher(lLine);
if(lMatcher.find()) {
    System.out.println(lMatcher.group());
}

The correct usage will be:

String filename = "C\\Windows\\SysWOW64\\ntdll.dll";
String file = filename.replace('\\', ' ');

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