Regular Expressions Regex modifiers (flags) VERBOSE / COMMENT / IgnorePatternWhitespace modifier


The modifier that allows using whitespace inside some parts of the pattern to format it for better readability and to allow comments starting with #:

/(?x)^          # start of string
  (?=\D*\d)     # the string should contain at least 1 digit 
  (?!\d+$)      # the string cannot consist of digits only
  \#            # the string starts with a hash symbol
  [a-zA-Z0-9]+ # the string should have 1 or more alphanumeric symbols
  $             # end of string

Example of a string: #word1here. Note the # symbol is escaped to denote a literal # that is part of a pattern.

Unescaped white space in the regular expression pattern is ignored, escape it to make it a part of the pattern.

Usually, the whitespace inside character classes ([...]) is treated as a literal whitespace, except in Java.

Also, it is worth mentioning that in PCRE, .NET, Python, Ruby Oniguruma, ICU, Boost regex flavors one can use (?#:...) comments inside the regex pattern.