Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Making strings safe for regex

 
Steve Wood
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • 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
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • 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).
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • 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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic