I am trying to match the <b>
tag or <b style=".....">
by using a regular expression like
<(/)?(b)[^>]*>
it not only matches the b
tag but all the tags starting with b
I am trying to match the <b>
tag or <b style=".....">
by using a regular expression like
<(/)?(b)[^>]*>
it not only matches the b
tag but all the tags starting with b
Try using a word boundary (\b
):
<(/)?(b\b)[^>]*>
This ensures that the next character after the <b
must not be a 'word' character (a letter, number or underscore).
Of course, this could match a tag like <b-foo>
, which might be a concern. In that case, I'd recommend using a lookahead like this:
<(/)?(b(?=[\s>]))[^>]*>
This ensures that the next character after the <b
must either be a whitespace character, or a >
.
Why don't you use this:
/<\/?b.*?>/g
Your regex:
/<(\/)?(b)[^>]*>/g
You may want to use the global modifier as per the syntax of your language of use. The one I've used is Javascript.
In JavaScript, to find and replace all <b> and </b>
tags, you'd do something like this:
const myStr = '<b>Hello</b>';
myStr.replace(/<[/]?(b)>/gi, '');
console.log(myStr); // Outputs 'Hello' with the bold tags removed
Hope that helps someone.