This week's book giveaway is in the Cloud/Virtualization forum.
We're giving away four copies of Kubernetes in Action and have Marko Luksa on-line!
See this thread for details.
Win a copy of Kubernetes in Action this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Making strings safe for regex  RSS feed

 
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
 
Rancher
Posts: 42972
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).
 
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
Boost this thread!