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
.
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.
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: \\.
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.
Use: \\ for one unescaped backslash. So in other words: String myString = "Here is a single backslash (\\) and here is a double backslash (\\\\)"; .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With