• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Making strings safe for regex

 
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys,

Is there a way to make strings safe for regex. What I mean is:

We have an application that uses regex to do some pattern finding. However, we don't want anything the user enters to interfere with this pattern finding.

So, what's happening is that some of the characters used by the user are creating regex searches (and throwing errors).

Is there a way to convert all regex special characters to safe versions? Or convert a subset?

Specifically, how do you convert a $ symbol to a safe version?

Cheers,

Steve
 
Rancher
Posts: 43026
76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All of the metacharacters need to be escaped by preceding them with a backslash. Some of those are ^ $ . [ ] { } ( ) * +

Note that inside of classes (i.e., inside [ ]), a slightly different set applies (e.g., "-" is special while "." is not).
 
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you're running Java 5, you can either escape the string with the static Pattern.quote(String) method, or compile it with the Pattern.LITERAL flag set. For earlier releases, you can just escape all punctuation characters:
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic