Skip to Main Content
Regular Expressions Cookbook, 2nd Edition
book

Regular Expressions Cookbook, 2nd Edition

by Jan Goyvaerts, Steven Levithan
August 2012
Intermediate to advanced content levelIntermediate to advanced
609 pages
19h 16m
English
O'Reilly Media, Inc.
Content preview from Regular Expressions Cookbook, 2nd Edition

9.2. Replace <b> Tags with <strong>

Problem

You want to replace all opening and closing <b> tags in a string with corresponding <strong> tags, while preserving any existing attributes.

Solution

This regex matches opening and closing <b> tags, with or without attributes:

<(/?)b\b((?:[^>"']|"[^"]*"|'[^']*')*)>
Regex options: Case insensitive
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

In free-spacing mode:

<
(/?)             # Capture the optional leading slash to backreference 1
b \b             # Tag name, with word boundary
(                # Capture any attributes, etc. to backreference 2
    (?: [^>"']   # Any character except >, ", or '
      | "[^"]*"  # Double-quoted attribute value
      | '[^']*'  # Single-quoted attribute value
    )*
)
>
Regex options: Case insensitive, free-spacing
Regex flavors: .NET, Java, XRegExp, PCRE, Perl, Python, Ruby

To preserve all attributes while changing the tag name, use the following replacement text:

<$1strong$2>
Replacement text flavors: .NET, Java, JavaScript, Perl, PHP
<\1strong\2>
Replacement text flavors: Python, Ruby

If you want to discard any attributes in the same process, omit backreference 2 in the replacement string:

<$1strong>
Replacement text flavors: .NET, Java, JavaScript, Perl, PHP
<\1strong>
Replacement text flavors: Python, Ruby

Recipe 3.15 shows the code needed to implement these replacements.

Discussion

The previous recipe (9.1) included a detailed discussion of many ways to match any XML-style tag. That frees this recipe to focus on a straightforward approach to search for a specific ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Regular Expressions, 3rd Edition

Mastering Regular Expressions, 3rd Edition

Jeffrey E.F. Friedl
Regular Expressions Cookbook

Regular Expressions Cookbook

Jan Goyvaerts, Steven Levithan

Publisher Resources

ISBN: 9781449327453Supplemental ContentErrata Page