Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to escape a Go string in a regular expression?

Tags:

regex

escaping

go

I'm wanting to match ^(@|\s)*{{string}}:? whereas {{string}} is dynamically defined. It may have periods and dashes and any number of things in it and I really need for it to be escaped.

PHP provides a preg_quote method that escapes all special characters safely. I was wondering if Go provides any sort of analog.

like image 427
donatJ Avatar asked Dec 11 '14 04:12

donatJ


People also ask

How do I escape characters in regex?

Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \.

How do you escape a Metacharacter in regex?

To match any of the metacharacters literally, one needs to escape these characters using a backslash ( \ ) to suppress their special meaning. Similarly, ^ and $ are anchors that are also considered regex metacharacters.

How do you escape from STR?

String newstr = "\\"; \ is a special character within a string used for escaping. "\" does now work because it is escaping the second " . To get a literal \ you need to escape it using \ .

What should be escaped regex?

In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped. Some flavors only use ^ and $ as metacharacters when they are at the start or end of the regex respectively. In those flavors, no additional escaping is necessary. It's usually just best to escape them anyway.


1 Answers

regexp.QuoteMeta does the deed.

like image 92
2 revs, 2 users 67% Avatar answered Sep 28 '22 01:09

2 revs, 2 users 67%