Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: Escaping an arbitrary (unknown) regular expression

Tags:

regex

groovy

I want to split a string via String.split(k) where k is an arbitrary string (read from intput). The problem is that k can be any string and thus may include regular expression operators, such as: "*[".

In such cases the split method fires an exception since the regular expression is not well formed.

What I am looking for is a way to escape any given k such that the resulting string can be safely passed on split().

Any thoughts?

like image 331
Itay Maman Avatar asked Jan 23 '10 12:01

Itay Maman


1 Answers

You can use Pattern.quote() to escape regex patterns.

like image 150
Michael Borgwardt Avatar answered Oct 05 '22 19:10

Michael Borgwardt