The zero-width assertion of a python regular expression

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.