Python Regular Expression 1, python Regular Expression

Source: Internet
Author: User

Python Regular Expression 1, python Regular Expression

To use a regular expression, you need to import the re module.

1 >>> import re2 >>> pattern=r'abc'3 >>> str='abcdefghijabc11111abc'4 >>> re.findall( pattern, str )5 ['abc', 'abc', 'abc']6 >>> 

R defines the regular expression rules. Here the string abc is matched.

Metacharacters ([]) match a range

>>> str="abc afc awc">>> pattern=r"a[bfw]c">>> re.findall( pattern, str )['abc', 'afc', 'awc']>>> pattern=r"a[bf]w">>> re.findall( pattern, str )[]>>> pattern=r"a[bf]c">>> re.findall( pattern, str )['abc', 'afc']>>> 

^: It starts with... and is used in brackets to indicate non-(inverse or exclusive)

1 >>> import re2 >>> str="ghostwu:hi my name is ghostwu, nice to meet you!"3 >>> pattern=r"ghostwu"4 >>> re.findall( pattern, str )5 ['ghostwu', 'ghostwu']6 >>> pattern=r"^ghostwu"7 >>> re.findall( pattern, str )8 ['ghostwu']9 >>> 
1 >>> str="abc"2 >>> pattern=r"a[b]c"3 >>> re.findall( pattern, str )4 ['abc']5 >>> pattern=r"a[^b]c"6 >>> re.findall( pattern, str )7 []8 >>> 

$: End...

>>> str="ghostwu:hi my name is ghostwu, nice to meet you! Hanmeimei: Hi,ghostwu">>> pattern=r"ghostwu">>> re.findall( pattern, str )['ghostwu', 'ghostwu', 'ghostwu']>>> pattern=r"ghostwu$">>> re.findall( pattern, str )['ghostwu']>>> 

$ Be used as a normal string matching in brackets

 1 >>> pattern=r"a[bcd$]" 2 >>> re.findall( pattern, 'ab' ) 3 ['ab'] 4 >>> re.findall( pattern, 'ac' ) 5 ['ac'] 6 >>> re.findall( pattern, 'ad' ) 7 ['ad'] 8 >>> re.findall( pattern, 'abe' ) 9 ['ab']10 >>> re.findall( pattern, 'a$' )11 ['a$']12 >>> 

Escape Character \

 1 >>> str="^ghostwu ^ghostwu ^ghostwu" 2 >>> pattern=r"^ghostwu" 3 >>> re.findall( pattern, str ) 4 [] 5 >>> pattern=r"ghostwu" 6 >>> re.findall( pattern, str ) 7 ['ghostwu', 'ghostwu', 'ghostwu'] 8 >>> pattern=r"\^ghostwu" 9 >>> re.findall( pattern, str )10 ['^ghostwu', '^ghostwu', '^ghostwu']11 >>> 

 

 

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.