Simple TextWrangler Grep Replace
Asked Answered
R

1

21

I am trying to replace all h2 tags containing the class "title" with h1:

<h2 class="title">Things</h2>

I'm using the Multi-File search in TextWranger with this:

<h2 class="title">[^>]*</h2>

I'm able to find everything, but when I hit replace, it replaces my titles with the grep crap.

BEFORE: <h2 class="title">Things</h2>
AFTER:    <h1 class="title">[^>]*</h1>

My problem is that the search not only replaces my tags but also replaces my content with [^>]*. I also tried this in Aptana and the same thing happened. I would appreciate some insight.

Rudin answered 2/2, 2012 at 4:34 Comment(0)
M
41

It looks like you're converting <h2 class="title"> to h1? You have to use a backreference in your "replace":

Search: <h2 class="title">([^>]*)</h2>

Replace: <h1 class="title">\1</h1> (aside- if it's a h1 do you still want to preserve the 'class="title"'?)

Note the brackets in the search regex, which save what's inside them.

Then you use \1 to pull them back out in the replace text (\1 for the first set of brackets, \2 for the second, ... )

Microsecond answered 2/2, 2012 at 5:20 Comment(2)
Thank you, the backreference was precisely my problem.Rudin
Depending on your regex engine you may need to use $1 to backreference the matching groupUnroof

© 2022 - 2024 — McMap. All rights reserved.