M. A.
M. A.

Reputation: 134

Can't use Regex in Java because of escape sequence error, how to remove the error

I have this regex :

^(([A-Z]:)|((\\|/){1,2}\w+)\$?)((\\|/)(\w[\w ]*.*))+\.([txt|exe]+)$

but every time I assign it to any string, Eclipse returns me invalid escape sequences, I have inserted a backward slash but it gives me the same error.

How to assign the above expression to string in java?

Upvotes: 3

Views: 361

Answers (2)

Christian Hujer
Christian Hujer

Reputation: 17945

Replace all "\\" with "\\\\". Java has no language support for regular expressions. So you'll need "\\" to get a backslash from the Compiler into the String. If the regular expression shall contain an escaped backslash, you need "\\\\".

final String re = "^(([A-Z]:)|((\\\\|/){1,2}\\w+)\\$?)((\\\\|/)(\\w[\\w ]*.*))+\\.([txt|exe]+)$"

Upvotes: 3

M A
M A

Reputation: 72844

Try the following:

String regex = "^(([A-Z]:)|((\\\\|/){1,2}\\w+)\\$?)((\\\\|/)(\\w[\\w ]*.*))+\\.([txt|exe]+)$";

The backslash character itself needs to be escaped as well, so you would end up with four \ characters.

Upvotes: 3

Related Questions