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.
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., \.
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.
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 \ .
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.
regexp.QuoteMeta
does the deed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With