Checking Whether The Match Is Preceded or Followed (or Not) By One or More Patterns Using Lookaround

Modern regular expression engines have the ability to “look around”. They can look ahead or look behind to see whether some text can be matched at the position the regex engine has reached in the subject string, without actually including that text in the regex match. This makes it possible to check whether the match is preceded or followed by certain text, or whether it is not preceded or followed by something.

To demonstrate this, we’ll create a regular expression that matches text between <b> tags in an HTML file. That text would appear bold in a web browser. The regex will match only the text between the tags. It will check for the presence of the tags without including them in the regex match. You can find this example as “Fields: lookaround” in the RegexMagic library.

The example uses the Match panel to build up the regular expression in a logical way, rather than from left to right. First we make the regex match the text we want. Then we add the requirement for that text to be preceded by an opening <b> tag and followed by a closing </b> tag.

  1. Click the New Formula button on the top toolbar to clear out all settings on the Samples, Match, and Action panels.
  2. On the Samples panel, paste in one new sample:
    Some <b>bold</b> text. And <i>italics</i>.
    We need to <b>match</b> this.
    Ignore <b>mismatched</i> <i>tags</b>.
  3. On the Match panel, click the Add First Field button to add field 1.
  4. Tick the “unlimited” checkbox to allow field 1 to match one or more characters.
  5. In the “pattern to match field” drop-down list, select “basic characters”. This field will match the actual text.
  6. Enter <> as the individual characters and check “match all characters except the selected ones”. This ensures the text cannot include HTML tags.
  7. Click the Add First Field button again to insert a new field 1 before the existing field, which changes its number to 2.
  8. Select “look around” in the “kind of field” drop-down list for field 1. When you do this, RegexMagic adds a new field 2 as the pattern for the lookaround. The original field changes its number to 3.
  9. Select “positive lookbehind” in the “kind of lookaround” drop-down list for field 1.
  10. For field 2, set “pattern to match field” to “literal text”.
  11. Enter <b> as the literal text and tick “case insensitive” for field 2.
  12. Click on the colored rectangle for field 3 to make the field buttons work on that field.
  13. Click the Add Next Field button Add Next Field to add field 6 after field 3.
  14. Select “look around” in the “kind of field” drop-down list for field 4. RegexMagic adds field 5 as the pattern for the lookaround.
  15. Select “positive lookbehind” in the “kind of lookaround” drop-down list for field 4.
  16. For field 5, set “pattern to match field” to “literal text”.
  17. Enter </b> as the literal text and tick “case insensitive” for field 5.



  18. On the Regex panel, select “Python 3.13” as your application, turn on free-spacing, and turn off mode modifiers. Click the Generate button, and you’ll get this regular expression:
    # 1. Look behind to assert that fields 2 to 2 can be matched ending at this position
    (?<=
      # 2. Literal text
      <b>
    )
    # 3. Basic characters
    [^<>]+
    # 4. Look ahead to assert that fields 5 to 5 can be matched starting at this position
    (?=
      # 5. Literal text
      </b>
    )
    Required options: Case insensitive; Free-spacing.
    Unused options: Dot doesn’t match line breaks; ^$ don’t match at line breaks.
  19. The Samples panel now highlights the text between the <b> tags, but not the tags themselves.
    Some <b>bold</b> text. And <i>italics</i>.
    We need to <b>match</b> this.
    Ignore <b>mismatched</i> <i>tags</b>.

This example only puts one field inside each lookaround. But you can add as many fields as you like. They form a sequence inside the lookaround.

When Lookaround Is Not Supported

Many regular expression flavors impose restrictions on lookbehind. Some only allow literal text inside lookbehind. Some allow alternatives of fixed length. A few allow quantifiers with an upper bound. Very few allow infinite quantifiers. The reason for this is that lookbehind requires the regular expression to work backwards. Only the JavaScript, .NET, and JGsoft regex engines support true right-to-left matching.

RegexMagic allows any of its patterns inside lookbehind. But when you generate the regular expression you may get an error that the pattern you’re trying to use doesn’t work inside lookbehind because of the limitations of your application’s regex engine.

Older regular expression flavors do not support lookbehind or even lookahead at all. With a traditional regular expression, to match text between HTML tags, the regex match needs to include the HTML tags. You can add a capturing group to retrieve the text between the tags. If the above example results in an error when you try to generate the regex for your preferred application, then you can modify it as follows:

  1. On the Match panel, change “kind of field” for field 1 to “a single pattern”. This effectively deletes field 1. Field 2 which matches <b> becomes the new field 1. The other fields also have their numbers decremented by one.
  2. The lookahead field is now field 3. Change its “kind of field” to “a single pattern” too. This removes the lookahead and field 4 becomes the new field 3.



  3. On the Action panel, click the New button to add a capturing group.
  4. Enter “content” as the group’s name. You should give your capturing groups a name even if your regex flavor does not support named capture.
  5. Set “what to capture” to “text matched by a field” and select “2 basic characters” in the “field” drop-down list. We now have a capturing group that will give us the text matched by field 2.
  6. You should now be able to generate the regular expression on the Regex panel:
    # 1. Literal text
    <b>
    # 2. content: Basic characters
    (?P<content>[^<>]+)
    # 3. Literal text
    </b>
    Required options: Case insensitive; Free-spacing.
    Unused options: Dot doesn’t match line breaks; ^$ don’t match at line breaks.
  7. The Samples panel now highlights the <b> tags and the text between them.
    Some <b>bold</b> text. And <i>italics</i>.
    We need to <b>match</b> this.
    Ignore <b>mismatched</i> <i>tags</b>.
  8. On the Use panel, in the Function drop-down list, choose “Get the part of a string matched by a named group”.
  9. Set the “group name” parameter to content. This produces Python code that we can use to extract the text between the <b> tags.
    match = re.search(
    	"""# 1. Literal text
    	<b>
    	# 2. content: Basic characters
    	(?P<content>[^<>]+)
    	# 3. Literal text
    	</b>""", 
    	subject, re.VERBOSE | re.IGNORECASE)
    if match:
        result = match.group("content")
    else:
        result = ""
    

Related Examples

Reference