Jump to content
  • entries
    25
  • comments
    0
  • views
    248

Regex Matching Modes (Page 17)


Most regular expression engines discussed in this tutorial support the following four matching modes:

Modifier Description
/i Makes the regex case-insensitive.
/s Enables "single-line mode," making the dot (.) match newlines.
/m Enables "multi-line mode," allowing caret (^) and dollar ($) to match at the start and end of each line.
/x Enables "free-spacing mode," where whitespace is ignored, and # can be used for comments.

Specifying Modes Inside The Regular Expression

You can specify these modes within a regex using mode modifiers. For example:

  • (?i) turns on case-insensitive matching.

  • (?s) enables single-line mode.

  • (?m) enables multi-line mode.

  • (?x) enables free-spacing mode.

Example:

(?i)hello matches "HELLO"

Turning Modes On and Off for Only Part of the Regex

Modern regex flavors allow you to apply modifiers to specific parts of the regex:

  • (?i-sm) turns on case-insensitive mode while turning off single-line and multi-line modes.

To apply a modifier to only a part of the regex, you can use the following syntax:

(?i)word(?-i)Word

This pattern makes "word" case-insensitive but "Word" case-sensitive.

Modifier Spans

Modifier spans apply modes to a specific section of the regex:

  • (?i:word) makes "word" case-insensitive.

  • (?i:case)(?-i:sensitive) applies mixed modes within the regex.

Example:

(?i:ignorecase)(?-i:casesensitive)

Summary

Understanding matching modes is essential for writing efficient and accurate regex patterns. By leveraging modes like case-insensitivity, single-line, multi-line, and free-spacing, you can create more flexible and maintainable regular expressions.

0 Comments


Recommended Comments

There are no comments to display.

×
×
  • Create New...

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.