DEV Community

Cover image for Cheatsheet for the Regex Cheatsheet, Part VIII: Pattern Modifiers
Analogy | Absence | Example
Analogy | Absence | Example

Posted on

Cheatsheet for the Regex Cheatsheet, Part VIII: Pattern Modifiers

Intro

I was recently doing a code challenge for a job interview that required me to strip out all nonalphabetic characters. "Ah! I should use Regular Expressions for this!" I thought in triumph, impressed that I even knew what regular expressions were. That fleeting moment of glory faded once I decided to brush up on regular expressions and landed on the encouragingly-named Regular Expressions Cheatsheet. I had no idea how to use it!

So, for people like me, here is a Cheatsheet for the Regex Cheatsheet, Part VIII: Pattern Modifiers

Alt Text

What are Pattern Modifiers?

Pattern modifiers aka flags modify the behavior of the regex search you are performing. Again, this will be better understood through example, so read on!

Anatomy of a regular expression

  1. Forward slashes go on either end like so: /something/
  2. Add g for "global" at the end to find every instance, like so: /something/g
  3. Add m to "multi line" to the beginning/end of each line, not just the beginning/end of each string, like /something/g or /something/gm

Pattern Modifiers

To illustrate pattern modifiers, let's revisit a regex from Groups & Ranges where we are searching for vowels:

[xyz] Range of characters (x or y or z)
  • [aeiou] is used in /[aeiou]/ (with no modifiers) to find the the only first vowel:

A lion roared


g Global match: Continue searching after the initial match
  • g can be added like this /[aeiou]/g to find all the lowercase vowels:

A lion roared


i Case Insensitive match
  • i can be added like this /[aeiou]/gi to find all the lowercase and uppercase vowels:

A lion roared


Dunce Corner

m Multiline

I don't get this. MDN Web Docs says:

"...if "m" is used, ^ and $ change from matching at only the start or end of the entire string to the start or end of any line within the string."


s Single line

Maybe this is explained in (this MDN Doc)[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/dotAll], but I still don't get it.


I don't think the following are supported in Javascript. Reach out in the comments in you know better.

x Allow comments and whitespace in pattern
U Ungreedy pattern

Top comments (0)