Reputation: 17304
Is it possible to search a string that is a regex, without escaping all the fancy characters?
For example, I want to find this string in my source file: ^[\d\| *]$
, without escaping \
, $
, etc.
I would like to just copy and paste the regex and get the result.
Upvotes: 2
Views: 4516
Reputation: 28934
There is an easy way to avoid special treatment of the characters
in Vim regular expressions. The \V
specifier allows to switch
interpretation of the rest of the pattern to the “very nomagic” mode,
which means that every character but the backslash is understood
literally.
Therefore, one can set the last search register accordingly:
:let @/ = '\V' . escape('^[\d\| *]$', '\')
and use n
and N
for searching immediately.
Upvotes: 4
Reputation: 172510
Supposing you have yanked the regexp to search for to the default register (@"
), you can do this:
/\V<C-R><C-R>=escape(@", '/\')<CR><CR>
The \V
starts a "very nomagic" search, where only atoms starting with a backslash have special, non-literal meaning. The escape()
renders all those contained backslashes ineffective (and escapes /
which would otherwise end the search pattern), so that this is a purely literal search. The text is inserted via Ctrl+R= into the search command line.
Upvotes: 1
Reputation: 84343
What you want is a grep that searches for matching strings, rather than attempting to match a regular expression. With GNU grep, you can invoke the command with the -F or --fixed-strings flags, or just invoke the command as fgrep instead. The following are all equivalent:
grep -F '^[\d\| *]$'
grep --fixed-strings '^[\d\| *]$'
fgrep '^[\d\| *]$'
Fixed-string searches are exactly what you need when you want to match code that represents a regular expression, or when you want a faster grep that doesn't need the advanced matching capability of a regular expression engine.
Upvotes: 4