0

Given this text:

<span class='green'>foobar</span> something <span class='red'>fizzle</span>

I need to somehow attain this:

<tagA>foobar</tagA> something <tabB>fizzle</tagB>

I basically have to match <span class='green'>*anything*</span> and be able to differentiate it from the red one as well. I have to take this green span on both ends and replace it with a fixed string, but somehow retain whatever text is between the two tags.

I swear I've looked around a ton but have no idea how to find the solution for this with regex.

2
  • Don't use Regex for HTML tags, And what about <span class='green'><span class='green'>foo</span>foobar<span class='green'>bar</span></span> ? ;). Commented Aug 12, 2015 at 7:34
  • It's not for HTML - it's for something else, I'm abstracting the concept so I can explain it easier. Commented Aug 12, 2015 at 7:35

1 Answer 1

1

This should do the trick

Replace

<span class='green'>(.*?)</span>

With

<tagA>$1</tagA>

And do something similar for the class with the value red

Update 1

Response to feedback "What if something contains a newline?"

If I remember correctly JavaScript does not support the "single line mode" / Dot matches line breaks.

<span class='green'>([\s\S]*?)</span>

Update 2

This tweaked regex allows

<span\s+class\s*=\s*['"]green['"]\s*>([^>]*)</\s*span\s*>
  • white space where the html spec is allowing it
  • accepts single as well as double quotes for the attribute values
  • matches the value between the tags using a negated character class which is qualified greedy resulting in better performance generally and is also supported by JavaScript
Sign up to request clarification or add additional context in comments.

4 Comments

This looked like it worked - thanks! Simpler than I thought.
What if something contains a newline?
Ok, the only remaining issue is nested tag groups - if there are any. Let OP decide.
@stribizhev As you know you can get clever with regexes and maybe support nested groups but If this support is needed I would switch to a HTML parsing library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.