Java Regexp patterns have double backslashes, how to store patterns in readable format
Would be great to have convenient way of storing patterns with sin开发者_StackOverflow社区gle 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
.
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 are interested in reading the expressions from a file, consider packaging the file inside the jar, and using Class.getResourceAsStream(...)
. AFAIK, that is still allowed in Java EE.
If you are working only in Java, my advise is to not sweat over it. Just store the regex as Java can understand them, that is with the annoying double \
.
IF and ONLY IF you want to store the regex to use them as a file input for different languages, then create the text file using the standard regex notation. But then you will have to create some sort of class that will use a char by char reading and take care of the escaping characters itself before adding them on the string to be used on the pattern matcher.
its a lot of work, (well actually not a lot, but damn if it will not be a nitpicky one) but you only have to do it once, and you could extend it for multiple languages, would be a good learning experience in my opinion. Do it wrong tho and you will suffer a lot debugging the little bastard.
Could be a nice if not vital addition to Java, some kinda flag that allows a text from file to be read directly as a regex standard string that would make the necessary changes itself. I have to check if someone has suggested this feature.
PS: just noticed that here you have to escape the \
to make it visible... that's weird...
精彩评论