0 Wide assertion: Used to find content before or after a specific content , but does not include the specific content itself .
For the 0-wide assertion, I think the most important concept is the position , the 0-wide assertion is used to specify a position that should satisfy a certain condition (which expression is met near it), and that position is not a character (so the match returns no results), just a position , so they are also called 0 wide assertions
0 Wide assertion This position of the emphasis is through a condition: the location near ( before or after ) exists or does not exist a (a can be an expression) to determine
Please forget its various names, we only remember the formula itself:
(? =exp): Match expression after this position exp
(? <=exp): Match expression in front of this position exp
(?! EXP): The expression after this position does not match exp
(? <!exp): This position is preceded by an unmatched expression exp
Note : Some areas only support partial zero-width assertions, such as online regular expressions
Here's an example:
>>> Import re
>>> str = ' <div>hello world</div> '
>>> Re.search (' (? =he). * ', str)
<_sre. Sre_match object; Span= (5,), match= ' Hello world</div> ' >
>>> Re.search (' (? =he). * (? <=ld) ', str)
<_sre. Sre_match object; Span= (5, +), match= ' Hello World ' >
>>> Re.search (' (?<=<div>). * (?=</div>) ', str)
<_sre. Sre_match object; Span= (5, +), match= ' Hello World ' >
>>> str = ' 3446456sdff456a '
>>> re.search (' [A-z]{3} (?! /d) ', str)
<_sre. Sre_match object; Span= (7,), match= ' SDF ' >
>>> re.search (' [A-z]{3} (?! [A-z]) ', str
<_sre. Sre_match object; Span= (8, one), match= ' DFF ' >
>>> Re.search (' (? <![ 0-9]) [0-9]{3} ', str)
<_sre. Sre_match object; Span= (0, 3), match= ' 344 ' > #匹配到了第一个位置
>>> Re.search (' (? <![ 0-9]) [0-9]{3} (?! [0-9]) ', str)
<_sre. Sre_match object; span=, match= ' 456 ' >
The zero-width assertion of a python regular expression