Groovy: escaping an arbitrary (unknown) regular expression

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

In such cases, the split method throws an exception because the regular expression is not well formed.

What I'm looking for is a way to avoid any given k so that the resulting string can be safely passed to split ().

Any thoughts?

+7
regex groovy
source share
1 answer

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

+8
source share

All Articles