PrivateUser
PrivateUser

Reputation: 4544

Finding and batch editing HTML elements' content in Sublime Text 2

I would like to replace link texts using regex in sublime text 2

my links look like this

<a href="#" class="link link1">This is a text for link 1</a>
<a href="#" class="link link2">This is a text for link 2</a>
<a href="#" class="link link3">This is a text for link 3</a>

I have more than 100 links in my page.

I have tried regex like this.

<a href="#" class="link.+">.+</a>

It works But it match the tags too.

Can anyone tell me how to match only this text This is a text for link * ?

Upvotes: 1

Views: 1754

Answers (3)

justhalf
justhalf

Reputation: 9117

As hinted by nhahtdh in his answer, you can do the replacement without using look-behind or look-ahead, use this regex to do replacement:

Search regex:

(<a href="#" class="link.+?">)[^<]+(\d)(</a>)

Replacement string:

\1Link number \2 has been replaced\3

That would replace this:

<a href="#" class="link link1">This is a text for link 1</a>
<a href="#" class="link link2">This is a text for link 2</a>
<a href="#" class="link link3">This is a text for link 3</a>

into this:

<a href="#" class="link link1">Link number 1 has been replaced</a>
<a href="#" class="link link2">Link number 2 has been replaced</a>
<a href="#" class="link link3">Link number 3 has been replaced</a>

The example I gave above also shows that it's possible to have capturing group in the anchor text matching, if you don't want it, you can remove it, and change the capturing group number accordingly.

Upvotes: 1

nhahtdh
nhahtdh

Reputation: 56829

I don't know why you only want to match the text, though. I can hardly think of any use case where that might be necessary. Usually capturing groups would be sufficient for most replacement scenarios.

If the text within the tag doesn't have any pattern, and the tag can contain arbitrary classes, then NO, it is NOT possible to do so. SublimeText seems to use Boost library, which doesn't support variable length look-behind.

If the tag are consistent (everything down to the spaces is the same), except for the link number in the class attribute, then it might be possible to certain extent:

(?<=<a href="#" class="link link\d">).+?(?=</a>)

If link followed by number class has 2 digits, you need to add in the corresponding look-behind:

(?:(?<=<a href="#" class="link link\d">)|(?<=<a href="#" class="link link\d\d">)).+?(?=</a>)

(\d{1,2} won't work in look-behind. The length is not finitely many, but the regex engine doesn't support it.)

Working screenshot

Upvotes: 3

Naveed S
Naveed S

Reputation: 5266

For matching This is a text for link followed by a space followed by a number, use This is a text for link \d+.

Edit: For matching any text between pair of opening and closing tags for links, use capture group like:

<a href="#" class="link.+?">(.+)</a>

$1 matches the text in between the tags.

Upvotes: 0

Related Questions