Regex quoting?

I have a string in a variable that I want to match literally as a regular expression. I want any special regex characters to be interpreted literally. In most environments there’s a “regex quote” operation that transforms a literal string into a corresponding regex. Do we have that for CMake?

CMake supports lua-style bracket syntax as an alternative to quoting with " characters:

I know about that feature, but I don’t see how it helps. If I understand that feature correctly, it’s a syntax for string literals. But as I wrote above, I don’t have a literal, I have a string in a variable that I want to match literally using one of the functions that takes a regex argument. if the string in that variable happens to contain a *, for example, I want it to match a * rather than being treated as a quantifier. I am looking for a function that knows about the special regex characters and escapes them so they will be interpreted literally, e.g. it replaces * with [*] or \* in the string.

To my knowledge, CMake does not provide anything to do what you’re asking.

[Quoting metacharacters](perlre - Perl regular expressions - Perldoc Browser metacharacters)

See a common idiom to disable or quote the special meanings of regular expression metacharacters in a string that you want to use for a pattern. Simply quote all non-“word” characters.

1 Like