wood burning stoves
The moose likes Java in General and the fly likes Force a string to ignore meta characters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Force a string to ignore meta characters" Watch "Force a string to ignore meta characters" New topic

Force a string to ignore meta characters

Dave Koontz

Joined: Jun 10, 2005
Posts: 3
I'm looking for a way to have Java ignore meta characters when compiling similar to the way you can say r"Aren't strings kinda/sorta great?" in Python and the compiler won't try to interpret the string. Is this even possible to indicate to javac or are you stuck putting in all the \\'s? Specifically this is for use with String.split() and any other regex based utilities.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

No, there's no way to tell Javac to ignore escape sequences in Strings.

[Jess in Action][AskingGoodQuestions]
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Note that there are two types of metacharacters here - metachars for the javac compiler (like \n) and metacharacters for the regex compiler (like \s). And many of these are metacharacters for both - e.g. since to get a completely literal \ in a regex you need to say \\\\. Ugh. Anyway, as EFH says there's no way to tell javac to ignore escape characters. However there is a way to auto-insert regex escapes so that the regex compiler intrepret a string literally rather than as an escape - using the Pattern.quote() method introduced in JDK 5:

If you're using a String literal to initialize this, it's of limited use, since so many regex metachars are also javac metachars, and write the literal you still need to escape the comiler metachars. It's still going to be confusing - probably more confusing with Pattern.quote(), simply because it's less familiar to most people. However quote() is very useful for escaping strings which were obtained from something other than a string liters. For example if a user has entered something in a search field, quote() will let you use it in a pattern without worrying about what funny characters might have been entered by the user.
[ August 02, 2005: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
I agree. Here's the link: http://aspose.com/file-tools
subject: Force a string to ignore meta characters
It's not a secret anymore!