Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vim, How to substitute within a subexpression?

I want to prepend all my classNames with o- without having to adjust every className by hand. I use Vim.

I know a substitution will do the job so I came up with this, which is obviously not working (and the reason I am here).

:%s/class="[^"]*"/\='class="'.substitute(submatch(0), '[^o-]*', 'o-'.submatch(1), 'g').'"'/g

Explanation:

  1. class="[^"] - matches all instances of class="foo bar baz"
  2. \='class="'.substitute(subexp).'"' - replaces the found instances class="subexp"
  3. subexp in two should repace each space separated class with the original className prepended with o-

All in all, in procedural terms, for each class="foo bar baz", replace each className with the className prepended with o-.

Thanks in advance.

(BONUS) EDIT: How can this be written to ignore or cope with classNames that already begin with o-, when encountered, so that o-o- is not a resulting edit.

like image 285
4Z4T4R Avatar asked Oct 24 '25 16:10

4Z4T4R


1 Answers

for the example

class="foo bar baz"

This line works:

%s/class="\zs[^"]*\ze"/\=join( map(split(submatch(0)),"'o-'.v:val"), ' ')/

So there are nested function calls:

  • I didn't use \< boundary because in case some "special" char in your classname, it will fail. E.g. # - or @. I don't know if it is the case in your language.
  • submatch(0) is the "foo bar baz"
  • split() makes it(each class) into list
  • map() add o- to each classname
  • join() turns the modified list back to string

So after executing this command, you should see:

class="o-foo o-bar o-baz"

Edit for the "Bonus" requirement:

We just need check each element(classname). Check the codes below, it should work for you:

%s/class="\zs[^"]*/\=join(map(split(submatch(0)),"(v:val=~'^o-'?'':'o-').v:val"))/

here we have:

(v:val=~'^o-'?'':'o-').v:val

If the element starts with o- then we don't add another o- any more.

like image 64
Kent Avatar answered Oct 27 '25 06:10

Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!