9.10. Syntax Flavors

  • In other programming languages

  • PCRE - Perl Compatible Regular Expressions

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

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

9.10.1. SetUp

>>> import re

9.10.2. Future

9.10.3. Enclosing

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

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

>>> data = '+48 123 456 789'
>>> result = re.match(r'[0-9]+', data)
const data = '+48 123 456 789'
const result = str.search(/[0-9]+/, data)
const data = '+48 123 456 789'
const pattern = new RegExp('[0-9]+');
const result = data.search(pattern)

9.10.4. Named Ranges

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

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

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

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

  • [: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.

>>> import re
>>> TEXT = 'hello world'
>>>
>>>
>>> re.findall(r'[:allnum:]', TEXT)
['l', 'l', 'l']
>>>
>>> re.findall(r'[:alpha:]', TEXT)
['h', 'l', 'l', 'l']

9.10.5. Range

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

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

  • Works in other languages, but not in Python

>>> import re
>>> TEXT = 'hello world'
>>>
>>>
>>> re.findall(r'[a-Z]', TEXT)
Traceback (most recent call last):
re.error: bad character range a-Z at position 1
>>>
>>> re.findall(r'[a-9]', TEXT)
Traceback (most recent call last):
re.error: bad character range a-9 at position 1

9.10.6. Group Backreference

  • $1 == \1

>>> HTML = '<span>Hello World</span>'
>>> re.findall(r'<(?P<tag>.+)>(?:.+)</(?P=tag)>', HTML)
['span']

9.10.7. References