• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Force a string to ignore meta characters

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, there's no way to tell Javac to ignore escape sequences in Strings.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic