7.25. Regex Flavors

  • In other programming languages

  • PCRE - Perl Compatible Regular Expressions

../../_images/regex-xkcd-standards.png

Figure 7.2. How Standards Proliferate. XKCD Standards [1]

7.25.1. SetUp

import re

7.25.2. Enclosing

  • In Python we use raw-string (r'...')

  • In JavaScript we use /pattern/flags or new RegExp(pattern, flags)

Python:

r'[a-z]+'

JavaScript:

/[a-z]+/

JavaScript:

new RegExp("[a-z]")

7.25.3. Flags

  • In Python we use raw-string (r'...')

  • In JavaScript we use /pattern/flags or new RegExp(pattern, flags)

Python:

re.findall(r'[a-z]+', TEXT, flags=re.I)
re.findall(r'[a-z]+', TEXT, flags=re.IGNORECASE)

re.findall(r'[a-z]+', TEXT, flags=re.I|re.M)
re.findall(r'[a-z]+', TEXT, flags=re.IGNORECASE|re.MULTILINE)

JavaScript:

/[a-z]+/i
/[a-z]+/im

JavaScript:

new RegExp("[a-z]", "i") new RegExp("[a-z]", "im")

7.25.4. Named Groups

  • In Python we use (?P<name>...)

  • In JavaScript we use (?<name>...)

Python:

r'(?P<mygroup>[a-z]+)'

JavaScript:

/(?<mygroup>[a-z]+)/

7.25.5. Range

  • [a-Z] == [a-zA-Z]

  • [a-9] == [a-zA-Z0-9]

  • Works in other languages, but not in Python

Python:

r'[a-z]'  # ok
r'[A-Z]'  # ok
r'[A-z]'  # ok

r'[a-Z]'  # re.PatternError: bad character range a-Z at position 1

JavaScript:

/[a-Z]/   // SyntaxError: Invalid regular expression: /[a-Z]/: Range out of order in character class

Perl:

/[a-Z]/

7.25.6. Group Backreference

  • \g<name> - Python

  • \g<1> - Python

  • \1

  • $1 - grep, egrep, Jetbrains IDE

In JavaScript name groups don't have ?P but only ?:

Python:

r'(?P<name>\d+)'

JavaScript:

/(?<name>\d+)/

7.25.7. Named Ranges

  • [:alpha:] - Alphabetic character [a-zA-Z]

  • [:alnum:] - Alphabetic and numeric character [a-zA-Z0-9]

  • [:blank:] - Space or tab

  • [:cntrl:] - Control character

  • [:digit:] - Digit

  • [:graph:] - Non-blank character (excludes spaces, control characters, and similar)

  • [:lower:] - Lowercase alphabetical character

  • [:print:] - Like [:graph:], but includes the space character

  • [:punct:] - Punctuation character

  • [:space:] - Whitespace character ([:blank:], newline, carriage return, etc.)

  • [:upper:] - Uppercase alphabetical

  • [:xdigit:] - Digit allowed in a hexadecimal number (i.e., 0-9a-fA-F)

  • [:word:] - A character in one of the following Unicode general categories Letter, Mark, Number, Connector_Punctuation

  • [:ascii:] - A character in the ASCII character set

In Python those Named Ranges does not work. String [:alpha:] will be interpreted literally as either: : or a or l or p or h or a.

TEXT = 'hello world'

re.findall(r'[:alpha:]', TEXT)
['h', 'l', 'l', 'l']

7.25.8. References