Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regexp patterns have double backslashes, how to store patterns in readable format

Tags:

java

regex

Would be great to have convenient way of storing patterns with single backslash. Some workarounds: store it in the file and use NIO to read. Cons: Java EE does not allow IO access. Store somehow in JNDI. Maybe new to java 5 Pattern.LITERAL flag can help? I want to work with normal pattern string, like \d, not \\d.

like image 277
core07 Avatar asked Apr 17 '10 09:04

core07


People also ask

What is double backslash in regex Java?

In Java escaping is done by double backslash because single backslash indicates special character (e.g. \n , \t ). It is escaping ${} symbols because these symbols have a special meaning in a regex, so escaping them tells the Java regex engine to treat them literally as those symbols and not their special meaning.

How do you escape a backslash in regex?

Because backslash \ has special meaning in strings and regexes, if we would like to tell Perl that we really mean a backs-slash, we will have to "escape" it, by using the "escape character" which happens to be back-slash itself. So we need to write two back-slashes: \\.

How do you escape a backslash in Java regex?

Characters can be escaped in Java Regex in two ways which are listed as follows which we will be discussing upto depth: Using \Q and \E for escaping. Using backslash(\\) for escaping.

How do you store backslash in strings?

Use: \\ for one unescaped backslash. So in other words: String myString = "Here is a single backslash (\\) and here is a double backslash (\\\\)"; .


1 Answers

the trouble is that \ is a special char in java when creating a String, regardless of regexp or not.

eg String s = "\t";

you cannot use this for arbitrary chars though, String s = "\a"; will give you a compile-time error. the valid chars are b, t, n, f, r, ", ' and \

therefore to get a literal \ in a string in java you need to escape it like so : \\. because of that, your only option is to NOT have these strings in java files, hence in an external file that is loaded by your java file. Pattern.LITERAL won't help at all because you still need a valid java string, which \d isn't.

like image 170
chris Avatar answered Oct 05 '22 07:10

chris