and half not
I'm trying to write a regex to add quotes around the ones without. I can
do this in perl, but not in vim, and I'd like to know what I'm doing
wrong because I've run across this problem before.
This was my attempt:
:%s/=\([^"]\+\)\{-}\([ >]\)/="\1"\2/g
My reasoning:
=\([^"]\+\) find and save stuff after an = that does not
have a "
\{-}I've never used this before, just found it
online, at first it seemed to do what I want it to do, make the \+
evaluation lazy
Any advice would be appreciated. Perhaps I'm not using \{-} correctly?
You've diagnosed where the problem lies...it's in the interaction
between your greedy
[^"]\+
and your non-greedy
\{-}
Greedy wins. :) The latter is an operator like the "\+", so you
likely want to convert your top bit to something like
[^"]\{-}
or possibly
[^"]\{-1,}
(which is "one or more, but as few as possible"...the embodiment
of your "I want to make \+ non-greedy" aim)
You can read up on the nuances of "\{-}" at
:help /\{
If I had to take a crack at it, I'd exploit the greediness rather
than shirk it, and do something like
:%s/=\([^" \t>]\+\)/="\1"/g
You might even be able to do something like
:%s/=\(\w\+\)/="\1"/g
depending on your attributes (what is considered a "word"
character for an HTML attribute would need to take into
consideration the "-" and the "." at a minimum, but these can
easily be added to the 'iskeyword' setting with ":set
iskeyword+=." and ":set iskeyword+=-")
The whole thing goes hooey if you have such matches outside tags,
which you might then want to modify your regexp to be something like
:%s/\(<[^=>]*\)=\([^" \t>]\+\)/\1="\2"/g
which should help to ensure some "inside-a-tag"ness context.
However, it only tidies one attribute for each tag, so you might
have to run it multiple times in the event you have multiple bad
attributes for a given tag like
Just a few ideas that might help. YMMV :)
-tim