0

I've been doing a lot of finding and replacing in Sublime Text and decided I needed to learn RegEx. So far, so good. I'm no expert by any means, but I'm learning quickly.

The trouble is knowing how to replace open-ended HTML matches.

For example, I wanted to find all <button>s that didn't have a role attribute. After some hacking and searching, I came up with the following pattern (see in action):

<button(?![^>]+role).*?>(.*?)

Great! Except, in the code base I'm working in, there are tons of results.
How do I do about replacing the results safely by injecting role=button at the end of <button, just before the closing > in the opening tag?

Desired results
Before: <button type="button">
After: <button type="button" role="button">

Before: <button class="btn-lg" type="button">
After: <button class="btn-lg" type="button" role="button">

Kevin Suttle
  • 8,358
  • 3
  • 33
  • 37

1 Answers1

1

You can capture everything before the ending > and put it back, before the insertion of role=button:

<(button(?![^>]+role).*?)>

This captures everything in the tag.

Replace by:

<$1 role="button">

The $1 contains what the first regex captured.

See the updated regexr.

Jerry
  • 70,495
  • 13
  • 100
  • 144