How to search for a string containing a regex in Vim? - search

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.

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.

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.

You can use the command line tool fgrep (“fast grep”),

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.

Related

Can I retrieve a single character from 'sed'?

With the sed command, is it possible to do internal string commands? in this case the actual lines are:
s/9G /9F6 09999F7 09999F8 09999F9 09999G /g
s/0G /0F6 09999F7 09999F8 09999F9 09999G /g
The number can be set using [09] but I didn't know if I could retrieve it from, say, & and use it before the F6 in something like the following:
s/[09]G /(&:0:1)F6 09999F7 09999F8 09999F9 09999G /g
This actual code does not work, by the way.
You are looking for a so called sub expression in the form of \(SUB_PATTERN\):
sed 's/\([09]\)G /\1F6 09999F7 09999F8 09999F9 09999G /g' file
From man sed:
s/regexp/replacement/
Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement.
The replacement may contain the special character & to refer to that portion of the pattern space which matched, and
the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.

vim: How to search for a hard-coded string (not regex)?

In order to search for a string in Vim, I click "/" and then type the word that I have to search. Vim looks at this string as regular expression. I want to know how to search a string, as it it, and not treat it as a regex.
Search commands always search for patterns (also known as regular expressions). You can make patterns more or less magic but cannot turn metacharacters completely off. If you have a fixed string you have to escape the characters that vim understands as metacharacters.
With the very nomagic mode of Vim's regular expressions (:help /\V), only the backslash is a special character that needs escaping.
So, prepend \V to your literal search, and (either manually or via escape(pattern, '\')) duplicate any backslashes. The following turns a "regular" search in to a literal one; you could define a mapping for that:
:let #/ = '\V' . escape(#/, '\')

vi replaces with empty when searching

In vi (from cygwin), when I do searching:
:%s/something
It just replaces the something with empty string like
:%s/something// .
I've googled for a while but nothing really mentions this. Is there anything I should add to the .vimrc or .exrc to make this work?
Thanks!
In vi and vim, when you search for a pattern, you can search it again by simply typing /. It is understood that the previous pattern has to be used when no pattern is specified for searching.
(Though, you can press n for finding next occurence)
Same way, when you give a source (pattern) and leave the replacement in substitute command, it assumes that the replacement is empty and hence the given pattern is replaced with no characters (in other words, the pattern is removed)
In your case, you should understand that % stand for whole file(buffer) and s for substitute. To search, you can simply use /, followed by a pattern. To substitute , you will use :s. You need not confuse searching and substituting. Hence, no need for such settings in ~/.exrc. Also, remember that / is enough to search the whole buffer and % isnt necessary with /. / searches the entire buffer implicitly.
You may also want to look at :g/Pattern/. Learn more about it by searching :help global or :help :g in command line.
The format of a substitution in vim is as follows:
:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]
In your case you have omitted the string from the substitution command and here what vim documentation stated about it:
If the {string} is omitted the substitute is done as if it's empty.
Thus the matched pattern is deleted. The separator after {pattern}
can also be left out then. Example: >
:%s/TESTING This deletes "TESTING" from all lines, but only one per line.
For compatibility with Vi these two exceptions are allowed:
"/{string}/" and "\?{string}?" do the same as "//{string}/r".
"\&{string}&" does the same as "//{string}/".
E146
Instead of the '/' which surrounds the pattern and replacement string, you can
use any other single-byte character, but not an alphanumeric
character, '\', '"' or '|'. This is useful if you want to include a
'/' in the search pattern or replacement string. Example: >
:s+/+//+
In other words :%s/something and :%s;something or :%s,something have all the same behavior because the / ; and , in the last examples are considered only as SIMPLE SEPARATOR

How to match using regular expression in matchstr function of vim script?

I'm trying to understand how VIM uses 'pattern' argument to 'matchstr' function.
I tried creating a pattern that matches either 'a' or 'b' but I'm unable to do this.
Here is what I tried:
:echo matchstr("ab", "a|b")
:echo matchstr("ab", "a\|b")
:echo matchstr("ab", "(a|b)")
:echo matchstr("ab", "(a|b)")
:echo matchstr("ab", "(a\|b)")
Note: 'set magic?' shows 'magic'
Vim uses a regex dialect, in which by default you need to escape special letters, if you need their regex feature. E.g. for OR you need to write \| and not like in perl regexes | This applies e.g. to the multi atom + and the OR atom |. (This can be changed by the regex atom \v which provides a more perl like regex dialect, see :h /\v)
Now you are using double quotes in your expression. When using double quotes, Vim will parse special characters and therefore remove one backslash, before the regex engine even sees them. Therefore, you need to either double your backslashes or use single quotes. This is explained at :h expr-quote

Vim Search/replace: what do I need to escape?

I'm trying to search and replace $data['user'] for $data['sessionUser'].
However, no matter what search string I use, I always get a "pattern not found" as the result of it.
So, what would be the correct search string? Do I need to escape any of these characters?
:%s/$data['user']/$data['sessionUser']/g
:%s/\$data\[\'user\'\]/$data['sessionUser']/g
I did not test this, but I guess it should work.
Here's a list of all special search characters you need to escape in Vim: `^$.*[~)+/
There's nothing wrong with with the answers given, but you can do this:
:%s/$data\['\zsuser\ze']/sessionUser/g
\zs and \ze can be used to delimit the part of the match that is affected by the replacement.
You don't need to escape the $ since it's the at the start of the pattern and can't match an EOL here. And you don't need to escape the ] since it doesn't have a matching starting [. However there's certainly no harm in escaping these characters if you can't remember all the rules. See :help pattern.txt for the full details, but don't try to digest it all in one go!
If you want to get fancy, you can do:
:%s/$data\['\zsuser\ze']/session\u&/g
& refers to the entire matched text (delimited by \zs and \ze if present), so it becomes 'user' in this case. The \u when used in a replacement string makes the next character upper-case. I hope this helps.
Search and replace in vim is almost identical to sed, so use the same escapes as you would with that:
:%s/\$data\['user'\]/$data['session']/g
Note that you only really need to escape special characters in the search part (the part between the first set of //s). The only character you need to escape in the replace part is the escape character \ itself (which you're not using here).
The [ char has a meaning in regex. It stands for character ranges. The $ char has a meaning too. It stands for end-line anchor. So you have to escape a lot of things. I suggest you to try a little plugin like this or this one and use a visual search.

Resources