Escaping regex metacharacters in Cypher

(Stephen Hall) #1

Is there a way to escape regex metacharacters (. + * ? etc) in a Cypher query? I want to do something like this:

MATCH (n), (m)
WHERE n.name =~ '.*\b' + m.name + '\b.*'

However there will be a problem if m.name happens to contain metacharacters, so I would like to call a function/procedure which would escape them before doing the regex operation, something like the quotemeta() function in Perl.

0 Likes

(Paul Drangeid) #2

Ok, its kind of ugly, but would this work?

WITH "Here is (my) * test string? with some + meta." as mystring
WITH *,["[","]","(" ,")", "?" ,"+" , "*" ,"."] as regexmetachars
WITH *,reduce(v = mystring, char in regexmetachars | apoc.text.replace(v, '[\\'+char+']{1}', '\\\\'+char)) as filteredstring
RETURN mystring,filteredstring
0 Likes

(Stephen Hall) #3

Yes it would, thanks! (At least until APOC gets an escapemeta() function :slightly_smiling_face:).

0 Likes