-3

I'm trying to write a regular expression that will match each individual class on HTML elements in an HTML file and allow me to append a string onto the end of each one. I'm using Atom, which is a basic text editor that lets you search with regular expressions.

My end goal is that I want to append a string onto each of the HTML classes on the page. I'm not sure what exactly should be matched by the regex to make the replacement easier - maybe match the character after each class and replace it with the new text plus the old character somehow? Is this even possible?

Examples:

<!-- Here I want to find 'container', then 'flex', then 'left'... -->
<div class="container flex left"></div>
<!-- And convert to... -->
<div class="container-new flex-new left-new"></div>


<!-- Here I want to match just on 'btn-1' -->
<label class="btn-1"></label>
<!-- and convert to: -->
<label class="btn-1-new"></label>

I know I need to use look-aheads and possibly look-behinds somehow, and now I've gone through a couple tutorials on how to use them, but am still struggling to write a regular expression to solve this problem.

  • 1
    [Do not use regex to parse HTML.](https://stackoverflow.com/a/1732454/4934172) – 41686d6564 stands w. Palestine Aug 14 '18 at 02:51
  • It's crazy how on Stack Overflow anytime someone sees HTML and regex they instantly assume that they're trying to parse it....This is just a simple find and append. – Khauri Aug 14 '18 at 02:53
  • @KhauriMcClain To parse something _in this context_ = to "find" something inside something else, which is what parsers are for. [This answer](https://stackoverflow.com/a/18724992/4934172) explains exactly how you might be trying to "find" something simple _with regex_ but you end up getting unexpected results. – 41686d6564 stands w. Palestine Aug 14 '18 at 02:56
  • @AhmedAbdelhameed He's doing this in a text editor, not an application program. – Barmar Aug 14 '18 at 02:59
  • @AhmedAbdelhameed That's not what parsing means...to parse roughly means to analyze, not to find. And regardless, this isn't an attempt to parse an arbitrary nested structure of HTML, but an attempt to modify a string. The structure of the HTML isn't important to this questions, thus why it's not trying to parse HTML. – Khauri Aug 14 '18 at 03:05
  • @Barmar You're right, I didn't pay attention to that. The advice stands though. If you're going to use regex to find and replace parts of an HTML file, you'll have to be very careful and aware that you're taking a risk. – 41686d6564 stands w. Palestine Aug 14 '18 at 03:05

1 Answers1

0

You could try:

Replace: (class="[^"]*)\bbtn-1\b
With: $1-new

\b matches a word boundary, so this ensures that you won't mistakenly match btn-10.

Barmar
  • 741,623
  • 53
  • 500
  • 612