Reputation: 1749
I want to match pair of words where one of them changes constantly (loop over an array of strings). The problem is that this word may contain metacharacters and I don't know which ones, so escaping them manually is a bit problem. Is there a way to construct a pattern of a string that already escapes all its metacharacters in java?
Upvotes: 0
Views: 309
Reputation: 920
You have a strings with meta-characters, but you don't know what meta-characters exactly. But in some way you know what meta-character is.
If you know all meta-characters which can appear in string, just list they in group: [\*abc\$\.\,\s]
(this group means in regexp that you can meet one of this characters, for example star, a, b, c, bucks ($), point, comma, whitespace). Also you can use ^
([^....]
) to invert logic.
Upvotes: 0
Reputation: 536399
If you are specifically talking about regular expressions, as implied by ‘matching words’, then the method you want is Pattern.quote.
In the more general sense, there is no way to automagically escape ‘metacharacters’ when you don't know what your target syntax is. In principle any character could have special non-literal meaning, and the way to escape it is completely dependent on the target syntax. In regular expressions, it's prefixing with a backslash, but for your question it is not clear whether you're talking about regular expressions.
Upvotes: 1