简体   繁体   中英

Disable string escaping (backslash hell)

I've started using Java regexes and I find I have to write patterns like this (contrived example):

C:\\\\\\\\windows\\\\\\\\system\\\\d+

to match

C:\\windows\\system32

Is there any way to use java regex without insane amounts of backslashes?

Use Pattern.quote(String s) (click for documentation)

It treats all meta characters in the passed String as literal characters (but you still must escape backslashes in construction of a String literal). This lets you type \\\\ instead of \\\\\\\\ to denote an actual/literal \\ in the regex pattern. But this also means that any other special characters will be interpreted literally as well (such as \\d+ in your example).

But in your example, you could use: Pattern.quote("C:\\\\windows\\\\system") + "\\\\d+";

Test it with this: System.out.println("C:\\\\windows\\\\system32".matches(Pattern.quote("C:\\\\windows\\\\system") + "\\\\d+"));

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