What's wrong with my REGEX while using VI editor? - regex

I have a text document like so:
<table width="10">
</table>
I open the document with the VI editor. I want to replace all instances of width="somenumber" with nothing. I issue this command in the VI editor:
:0,$s/width="[\d]+"//gc
VI says no pattern found. I also tried this and it doens't work:
0,$s/width="[0-9]+"//gc
This one below worked:
:0,$s/width="\d\d"//gc
What's wrong with my first two expressions?

You have two errors in your regexp!
First, use \d without []s around it. You probably mix it with character classes like :alpha:, :digit:, etc.
Second, Escape the + sign. By default you should escape it.
So your regexp would be:
:0,$s/width="\d\+"//gc
And, please, read help before posting on stackoverflow:
:h :s
You may also be interested in this help section:
:h magic

It will only work with widths of two digits, won't it?

You want:
:0,$s/ width="\d\+"//gc
\d isn't recognized inside a character class (or rather, it's recognized as the letter d), and + without a backslash isn't recognized as a metacharacter by vim's BRE. You also probably want the space before width to be eliminated.

Related

Search string enclosed in quotes in Vim

In vim I need to search all strings in quotes e.g. 'foo'
Does one see the problem in this regex? E486: Pattern not found \'([^']*)'
:\/'([^']*)'
Regex Tester
First problem is that your use of find is a bit confusing. If you want
to just find, use /. The colon is not necessary (which indicates
command mode). If you're using the find as a range (basically the same
thing, / is just an empty command with a range) you can use the colon,
but either way escaping the first slash is not necessary.
The other main problem is that parenthesis by default need to be escaped
if you meant a capturing group. All of this is dependant on your
'magic' option reading the help for the /magic topic (you can do a
:h magic) is highly recommended. With "vanilla" Vim settings, the
regex you need looks live this:
/'\([^']*\)'
With very magic enable (by using the \v atom) this can be simplified
to your original design:
/\v'([^']*)'
Alternatively you can use
\v'(\a+)'
this regex performs similar than yours, except when nested quotes are encountered. In the text:
The user's first 'answer'.
The regex \v'(\a+)' will capture answer while your original regex (corrected by sidyll) \v'([^']*)' will capture 's first '.

Vim regex to substitute/escape pipe characters

Let's suppose I have a line:
a|b|c
I'd like to run a regex to convert it to:
a\|b\|c
In most regex engines I'm familiar with, something like s%\|%\\|%g should work. If I try this in Vim, I get:
\|a\||\|b\||\|c
As it turns out, I discovered the answer while typing up this question. I'll submit it with my solution, anyway, as I was a bit surprised a search didn't turn up any duplicates.
vim has its own regex syntax. There is a comparison with PCRE in vim help doc (see :help perl-patterns).
except for that, vim has no magic/magic/very magic mode. :h magic to check the table.
by default, vim has magic mode. if you want to make the :s command in your question work, just active the very magic:
:s/\v\|/\\|/g
Vim does the opposite of PCRE in this regard: | is a literal pipe character, with \| serving as the alternation operator. I couldn't find an appropriate escape sequence because the pipe character does not need to be escaped.
The following command works for the line in my example:
:. s%|%\\|%g
If you use very-magic (use \v) you'll have the Perl/pcre behaviour on most special characters (excl. the vim specifics):
:s#\v\|#\\|#g

Perform a non-regex search/replace in vim

When doing search/replace in vim, I almost never need to use regex, so it's a pain to constantly be escaping everything, Is there a way to make it default to not using regex or is there an alternative command to accomplish this?
As an example, if I want to replace < with <, I'd like to just be able to type s/</</g instead of s/\</\&lt\;/g
For the :s command there is a shortcut to disable or force magic. To turn off magic use :sno like:
:sno/search_string/replace_string/g
Found here: http://vim.wikia.com/wiki/Simplifying_regular_expressions_using_magic_and_no-magic
Use this option:
set nomagic
See :help /magic
The problem is primarily caused by confusion about the role of the & in the replacement string. The replacement string is not a reg-ex, although it has some special characters, like &. You can read about role of & in replacement string here: :h sub-replace-special .
I suspect the main problem for OP is not necessarily typing the extra backslashes, but rather remembering when a backslash is needed and when not. One workaround may be to start making use of "replacement expressions" when unsure. ( See :h sub-replace-expression.) This requires putting a `\=' in replacement string but for some people it may give you more natural control over what's being substituted, since putting a string literal in single quotes will give you the replacement string you want. For example, this substitute does what OP wants:
:s/</\='<'/g
If you want to search literally, you can use the \V regex atom. This almost does what you want, except that you also need to escape the backslash. You could define your own search command, that would search literally. Something like this:
:com! -nargs=1 Search :let #/='\V'.escape(<q-args>, '\/')| normal! n
And then use :Search /foobar/baz
For Substitute, you could then after a :Search command simply use
:%s//replace/g
since then Vim would implicitly pick up the last search item and use the for replacing.
(Just want to give you some ideas)
Here’s how to disable regular expression search/replace only in command mode:
autocmd CmdWinEnter * set nomagic
autocmd CmdWinLeave * set magic
All plugins that depends on regular expression such as white-space remover should works as usual.
Have you enabled magic?
:set magic
Try the Edit Find and replace on the menu bar.

Adding "/index.html" to paths in Vim

I'm trying to append "/index.html" to some folder paths in a list like this:
path/one/
/another/index.html
other/file/index.html
path/number/two
this/is/the/third/path/
path/five
sixth/path/goes/here/
Obviously the text only needs to be added where it does not exist yet. I could achieve some good results with (vim command):
:%s/^\([^.]*\)$/\1\/index.html/
The only problem is that after running this command, some lines like the 1st, 5th and 7th in the previous example end up with duplicated slashes. That's easy to solve too, all I have to do is search for duplicates and replace with a single slashes.
But the question is:
Isn't there a better way to achieve the correct result at once?
I'm a Vim beginner, and not a regex master also. Any tips are really appreciated!
Thanks!
So very close :)
Just add an optional slash to the end of the regex:
\/\?
Then you need to change the rest of the pattern to a non-greedy match so that it ignores a trailing slash. The syntax for a non-greedy match in vim (replacing the *) is:
\{-}
So we end up with:
:%s/^\([^\.]\{-}\)\/\?$/\1\/index.html/
(Doesn't hurt to be safe and escape the period.)
Vim's regex supports the ability to match a bit of text foo if it does or doesn't precedes or follows some other text bar without matching bar, and this is exactly the sort of thing you're looking for. Here you want to match the end of line with an optional /, but only if the / isn't followed by index.html, and then replace it with /index.html. A quick look at Vim's help tells me \#<! is exactly what to use. It tells Vim that the preceding atom must be in the text but not in what's matched. With a little experimentation, I get
:%s;/\?\(index\.html\)\#<!$;/index.html;
I use ; to delimit the parts of the :s command so that I don't have to escape any / in the regex or replacement expression. In this particular situation, it's not a big deal though.
The / is optional, and we say so with \?.
We need to group index.html together because otherwise our special \#<! would only affect the l otherwise.

(g)vim replace regex

I'm looking for a regex that will change sth. like this:
print "testcode $testvar \n";
in
printnlog("testcode $testvar \n");
I tried %s/print\s*(.\{-});/printnlog(\1);/g but gvim says
print\s*(.\{-});
doesn't match.
Where is my fault?
Is it ok to use '*' after '\s' because later '{-};' will stop the greed?
Thanks in advance.
In vim you have to prepend (, ) and | with backslash, so try
:%s/print\s*\(.\{-}\);/printnlog(\1);/g
MBO's answer works great, but sometimes I find it easier to use the "very magic" option \v so I don't have to escape everything; makes the regex a little more readable.
See also:
:h /\v in Vim
http://briancarper.net/blog/vim-regexes-are-awesome
While you can create capture groups (like you're doing), I think the easiest approach is to do the job in multiple steps, with very simple regexes and "flag" words. For example:
:%s/print "testcode.*/printnlog(XXX&XXX);/
:%s/XXXprint //
:%s/;XXX//
In these examples, I use "XXX" to indicate boundaries that should later be trimmed (you can use anything that doesn't appear in your code). The ampersand (&) takes the entire match string and inserts it into the replacement string.
I don't know about other people, but I can type and execute these three regexes faster than I can think through a capture group.
Is this sufficient for your needs?
%s/print\s*\("[^"]*"\)/printnlog(\1)