Question

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, i.e:

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, i.e:

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

Was it helpful?

Solution

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)) {

OTHER TIPS

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('\\', ' ');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top