• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Force a string to ignore meta characters

 
Dave Koontz
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, there's no way to tell Javac to ignore escape sequences in Strings.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic