Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

{} () [] and re.match re.search in regular expressions

Shulou Source: shulou.com Published: 2022-06-03 06:49:40 09月15日 Update

1. Regular expressions

() is to extract matching strings. There are several () in the expression, there are several corresponding matching strings.

(\s*) A string representing consecutive spaces.

(\d*) represents a continuous number, similar to [0-9]+

[] is the character range that defines the match. For example,[a-zA-Z0-9] indicates that the characters in the corresponding position should match English characters and numbers. [\s*] indicates a space or an *.

{} is generally used to indicate the length of the match, such as\s{3} for matching three spaces,\s[1,3] for matching one to three spaces.

(0-9)Matches '0-9' itself. [0-9]* Matching digits (note *, can be empty)[0-9]+ matching digits (note +, can not be empty){1-9} is written incorrectly.

[0-9]{0,9} represents a numeric string of length 0 to 9

Examples of []* and []+:

[]* can return control, that is, can not find the value, but [0-9]+ can not be empty, if empty return error

>>> c='GET /diviner? pin=1123066825_m&p='

>>> r=re.search('p=([0-9]+)',c)

>>> print r.group(1)

Traceback (most recent call last):

File "", line 1, in

AttributeError: 'NoneType' object has no attribute 'group'

>>> print r

None

>>> r=re.search('p=([0-9]*)',c)

>>> print r.group(1)

---Return empty here

2.re mathc search Description

match () function only checks if RE matches at the beginning of string,

search() scans the entire string for a match;

>>> a='123aaabcabcabc'

>>> import re

>>> re.search('abc',a)

>>> re.mathc('abc',a)

Traceback (most recent call last):

File "", line 1, in

AttributeError: 'module' object has no attribute 'mathc'

>>> re.match('abc',a)

>>> b=re.match('abc',a)

>>> print b

None

>>> b=re.match('1',a)

>>> pint b

File "", line 1

pint b

^

SyntaxError: invalid syntax

>>> print b

() in the role of group groups---mainly plays the role of grouping

>>> c='GET /diviner? pin=1123066825_m&p=61234'

>>> r=re.search('p=((\d*))',c)

>>> print c.group(0)

Traceback (most recent call last):

File "", line 1, in

AttributeError: 'str' object has no attribute 'group'

>>> print r.group(0)

p=61234

>>> r=re.search('p=((\d*))',c)

>>> r=re.search('p=([0-9]*)',c)

>>> r=re.search('p=[0-9]*',c)

>>> print r.group

>>> print r.group(0)

p=61234

>>> print r.group (1)---No parenthesis No grouping

Traceback (most recent call last):

File "", line 1, in

IndexError: no such group

>>> r=re.search('p=([0-9]*)',c)

>>> print r.group(1)

61234

Tags: Character number string space expression three position function error length grouping regular writing function parenthesis example range English control detection Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL OPPO Reno Shulou Technology macOS Docker