RegEx正则表达

2020-04-25  本文已影响0人  明月海子

介绍演示

正则表达式 (Regular Expression) 又称 RegEx, 是用来匹配字符的一种工具. 在一大串字符中寻找你需要的内容. 它常被用在很多方面, 比如网页爬虫, 文稿整理, 数据筛选等等. 最简单的一个例子, 比如我需要爬取网页中每一页的标题. 而网页中的标题常常是这种形式.

<title>我是标题</ title>

而且每个网页的标题各不相同, 我就能使用正则表达式, 用一种简单的匹配方法, 一次性选取出成千上万网页的标题信息. 正则表达式绝对不是一天就能学会和记住的, 因为表达式里面的内容非常多, 强烈建议, 现在这个阶段, 你只需要了解正则里都有些什么, 不用记住, 等到你真正需要用到它的时候, 再反过头来, 好好琢磨琢磨, 那个时候才是你需要训练自己记住这些表达式的时候.

简单的匹配

正则表达式无非就是在做这么一回事. 在文字中找到特定的内容, 比如下面的内容. 我们在 “dog runs to cat” 这句话中寻找是否存在 “cat” 或者 “bird”.

# matching string
pattern1 = "cat"
pattern2 = "bird"
string = "dog runs to cat"
print(pattern1 in string)    # True
print(pattern2 in string)    # False

但是正则表达式绝非不止这样简单的匹配, 它还能做更加高级的内容. 要使用正则表达式, 首先需要调用一个 python 的内置模块 re. 然后我们重复上面的步骤, 不过这次使用正则. 可以看出, 如果 re.search() 找到了结果, 它会返回一个 match 的 object. 如果没有匹配到, 它会返回 None. 这个 re.search() 只是 re 中的一个功能, 之后会介绍其它的功能.

import re

# regular expression
pattern1 = "cat"
pattern2 = "bird"
string = "dog runs to cat"
print(re.search(pattern1, string))  # <_sre.SRE_Match object; span=(12, 15), match='cat'>
print(re.search(pattern2, string))  # None

<ins class="adsbygoogle" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-4601203457616636" data-ad-slot="3397817325" data-adsbygoogle-status="done" data-overlap-observer-io="false" style="display: block; text-align: center; height: 159px; width: 617px;"><ins id="aswift_2_expand" style="display: inline-table; border: none; height: 159px; margin: 0px; padding: 0px; position: relative; visibility: visible; width: 617px; background-color: transparent;"><ins id="aswift_2_anchor" style="display: block; border: none; height: 159px; margin: 0px; padding: 0px; position: relative; visibility: visible; width: 617px; background-color: transparent; overflow: hidden;"><iframe id="aswift_2" name="aswift_2" sandbox="allow-forms allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" width="617" height="159" frameborder="0" src="https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-4601203457616636&output=html&h=159&slotname=3397817325&adk=3401585631&adf=960100261&w=636&fwrn=4&lmt=1583377291&rafmt=11&psa=0&guci=2.2.0.0.2.2.0.0&format=636x159&url=https%3A%2F%2Fmorvanzhou.github.io%2Ftutorials%2Fpython-basic%2Fbasic%2F13-10-regular-expression%2F&flash=0&wgl=1&dt=1587802197986&bpp=3&bdt=388&idt=102&shv=r20200422&cbv=r20190131&ptt=9&saldr=aa&abxe=1&prev_fmts=700x90%2C250x250&correlator=3466323590182&frm=20&pv=1&ga_vid=1212726724.1583946939&ga_sid=1587802198&ga_hid=1016610859&ga_fc=0&iag=0&icsg=9130715816&dssz=30&mdo=0&mso=0&rplot=4&u_tz=480&u_his=9&u_java=0&u_h=1080&u_w=1920&u_ah=1040&u_aw=1920&u_cd=24&u_nplug=3&u_nmime=4&adx=484&ady=2282&biw=1903&bih=937&scr_x=0&scr_y=0&eid=21065214&oid=3&pvsid=322963587975057&pem=821&ref=https%3A%2F%2Fmorvanzhou.github.io%2Ftutorials%2Fpython-basic%2Fbasic%2F&rx=0&eae=0&fc=896&brdim=0%2C0%2C0%2C0%2C1920%2C0%2C1920%2C1040%2C1920%2C937&vis=1&rsz=%7C%7CeEbr%7C&abl=CS&pfx=0&fu=8344&bc=31&ifi=3&uci=a!3&btvi=2&fsb=1&xpc=I9411BAsV6&p=https%3A//morvanzhou.github.io&dtd=106" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" data-google-container-id="a!3" data-google-query-id="CMnao5CQg-kCFQQaKgodoykIYA" data-load-complete="true" style="left: 0px; position: absolute; top: 0px; border: 0px; width: 617px; height: 159px;"></iframe></ins></ins></ins>

灵活匹配

除了上面的简单匹配, 下面的内容才是正则的核心内容, 使用特殊的 pattern 来灵活匹配需要找的文字.

如果需要找到潜在的多个可能性文字, 我们可以使用 [] 将可能的字符囊括进来. 比如 [ab] 就说明我想要找的字符可以是 a 也可以是 b. 这里我们还需要注意的是, 建立一个正则的规则, 我们在 pattern 的 “” 前面需要加上一个 r 用来表示这是正则表达式, 而不是普通字符串. 通过下面这种形式, 如果字符串中出现 “run” 或者是 “ran”, 它都能找到.

# multiple patterns ("run" or "ran")
ptn = r"r[au]n"       # start with "r" means raw string
print(re.search(ptn, "dog runs to cat"))    # <_sre.SRE_Match object; span=(4, 7), match='run'>

同样, 中括号 [] 中还可以是以下这些或者是这些的组合. 比如 [A-Z] 表示的就是所有大写的英文字母. [0-9a-z] 表示可以是数字也可以是任何小写字母.

print(re.search(r"r[A-Z]n", "dog runs to cat"))     # None
print(re.search(r"r[a-z]n", "dog runs to cat"))     # <_sre.SRE_Match object; span=(4, 7), match='run'>
print(re.search(r"r[0-9]n", "dog r2ns to cat"))     # <_sre.SRE_Match object; span=(4, 7), match='r2n'>
print(re.search(r"r[0-9a-z]n", "dog runs to cat"))  # <_sre.SRE_Match object; span=(4, 7), match='run'>

<ins class="adsbygoogle" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-4601203457616636" data-ad-slot="3397817325" data-adsbygoogle-status="done" data-overlap-observer-io="false" style="display: block; text-align: center; height: 123px; width: 636px;"><ins id="aswift_3_expand" style="display: inline-table; border: none; height: 123px; margin: 0px; padding: 0px; position: relative; visibility: visible; width: 636px; background-color: transparent;"><ins id="aswift_3_anchor" style="display: block; border: none; height: 123px; margin: 0px; padding: 0px; position: relative; visibility: visible; width: 636px; background-color: transparent; overflow: hidden;"><iframe id="aswift_3" name="aswift_3" sandbox="allow-forms allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" width="636" height="123" frameborder="0" src="https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-4601203457616636&output=html&h=159&slotname=3397817325&adk=3401585631&adf=3131098319&w=636&fwrn=4&lmt=1583377291&rafmt=11&psa=0&guci=2.2.0.0.2.2.0.0&format=636x159&url=https%3A%2F%2Fmorvanzhou.github.io%2Ftutorials%2Fpython-basic%2Fbasic%2F13-10-regular-expression%2F&flash=0&wgl=1&dt=1587802197989&bpp=2&bdt=391&idt=111&shv=r20200422&cbv=r20190131&ptt=9&saldr=aa&abxe=1&prev_fmts=700x90%2C250x250%2C636x159&correlator=3466323590182&frm=20&pv=1&ga_vid=1212726724.1583946939&ga_sid=1587802198&ga_hid=1016610859&ga_fc=0&iag=0&icsg=9130715816&dssz=30&mdo=0&mso=0&rplot=4&u_tz=480&u_his=9&u_java=0&u_h=1080&u_w=1920&u_ah=1040&u_aw=1920&u_cd=24&u_nplug=3&u_nmime=4&adx=484&ady=3137&biw=1903&bih=937&scr_x=0&scr_y=0&eid=21065214&oid=3&pvsid=322963587975057&pem=821&ref=https%3A%2F%2Fmorvanzhou.github.io%2Ftutorials%2Fpython-basic%2Fbasic%2F&rx=0&eae=0&fc=896&brdim=0%2C0%2C0%2C0%2C1920%2C0%2C1920%2C1040%2C1920%2C937&vis=1&rsz=%7C%7CeEbr%7C&abl=CS&pfx=0&fu=8344&bc=31&ifi=4&uci=a!4&btvi=3&fsb=1&xpc=RnhynsXM2u&p=https%3A//morvanzhou.github.io&dtd=115" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" data-google-container-id="a!4" data-google-query-id="CLy5o5CQg-kCFdgYKgodU_ACLQ" data-load-complete="true" style="left: 0px; position: absolute; top: 0px; border: 0px; width: 636px; height: 123px;"></iframe></ins></ins></ins>

按类型匹配

除了自己定义规则, 还有很多匹配的规则时提前就给你定义好了的. 下面有一些特殊的匹配类型给大家先总结一下, 然后再上一些例子.

下面就是具体的举例说明啦.

# \d : decimal digit
print(re.search(r"r\dn", "run r4n"))           # <_sre.SRE_Match object; span=(4, 7), match='r4n'>
# \D : any non-decimal digit
print(re.search(r"r\Dn", "run r4n"))           # <_sre.SRE_Match object; span=(0, 3), match='run'>
# \s : any white space [\t\n\r\f\v]
print(re.search(r"r\sn", "r\nn r4n"))          # <_sre.SRE_Match object; span=(0, 3), match='r\nn'>
# \S : opposite to \s, any non-white space
print(re.search(r"r\Sn", "r\nn r4n"))          # <_sre.SRE_Match object; span=(4, 7), match='r4n'>
# \w : [a-zA-Z0-9_]
print(re.search(r"r\wn", "r\nn r4n"))          # <_sre.SRE_Match object; span=(4, 7), match='r4n'>
# \W : opposite to \w
print(re.search(r"r\Wn", "r\nn r4n"))          # <_sre.SRE_Match object; span=(0, 3), match='r\nn'>
# \b : empty string (only at the start or end of the word)
print(re.search(r"\bruns\b", "dog runs to cat"))    # <_sre.SRE_Match object; span=(4, 8), match='runs'>
# \B : empty string (but not at the start or end of a word)
print(re.search(r"\B runs \B", "dog   runs  to cat"))  # <_sre.SRE_Match object; span=(8, 14), match=' runs '>
# \\ : match \
print(re.search(r"runs\\", "runs\ to me"))     # <_sre.SRE_Match object; span=(0, 5), match='runs\\'>
# . : match anything (except \n)
print(re.search(r"r.n", "r[ns to me"))         # <_sre.SRE_Match object; span=(0, 3), match='r[n'>
# ^ : match line beginning
print(re.search(r"^dog", "dog runs to cat"))   # <_sre.SRE_Match object; span=(0, 3), match='dog'>
# $ : match line ending
print(re.search(r"cat$", "dog runs to cat"))   # <_sre.SRE_Match object; span=(12, 15), match='cat'>
# ? : may or may not occur
print(re.search(r"Mon(day)?", "Monday"))       # <_sre.SRE_Match object; span=(0, 6), match='Monday'>
print(re.search(r"Mon(day)?", "Mon"))          # <_sre.SRE_Match object; span=(0, 3), match='Mon'>

如果一个字符串有很多行, 我们想使用 ^ 形式来匹配行开头的字符, 如果用通常的形式是不成功的. 比如下面的 “I” 出现在第二行开头, 但是使用 r"^I" 却匹配不到第二行, 这时候, 我们要使用 另外一个参数, 让 re.search() 可以对每一行单独处理. 这个参数就是 flags=re.M, 或者这样写也行 flags=re.MULTILINE.

<ins data-ad-format="auto" class="adsbygoogle adsbygoogle-noablate" data-ad-client="ca-pub-4601203457616636" data-adsbygoogle-status="done" data-overlap-observer-io="false" style="display: block; margin: auto; background-color: transparent;"><ins id="aswift_8_expand" style="display: inline-table; border: none; height: 159px; margin: 0px; padding: 0px; position: relative; visibility: visible; width: 636px; background-color: transparent;"><ins id="aswift_8_anchor" style="display: block; border: none; height: 159px; margin: 0px; padding: 0px; position: relative; visibility: visible; width: 636px; background-color: transparent;"><iframe id="aswift_8" name="aswift_8" sandbox="allow-forms allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" width="636" height="159" frameborder="0" src="https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-4601203457616636&output=html&h=159&adk=1744626125&adf=2663990526&w=636&lmt=1583377291&num_ads=1&rafmt=16&sem=mc&pwprc=9194589492&psa=0&guci=2.2.0.0.2.2.0.0&ad_type=text_image&format=636x159&url=https%3A%2F%2Fmorvanzhou.github.io%2Ftutorials%2Fpython-basic%2Fbasic%2F13-10-regular-expression%2F&flash=0&pra=3&wgl=1&fa=27&adsid=NT&dt=1587802198495&bpp=2&bdt=897&idt=2&shv=r20200422&cbv=r20190131&ptt=9&saldr=aa&abxe=1&prev_fmts=700x90%2C250x250%2C636x159%2C636x159%2C300x250%2C0x0&nras=2&correlator=3466323590182&frm=20&pv=1&ga_vid=1212726724.1583946939&ga_sid=1587802198&ga_hid=1016610859&ga_fc=0&iag=0&icsg=9130715816&dssz=30&mdo=0&mso=0&u_tz=480&u_his=9&u_java=0&u_h=1080&u_w=1920&u_ah=1040&u_aw=1920&u_cd=24&u_nplug=3&u_nmime=4&adx=484&ady=4507&biw=1903&bih=937&scr_x=0&scr_y=0&eid=21065214&oid=3&pvsid=322963587975057&pem=821&ref=https%3A%2F%2Fmorvanzhou.github.io%2Ftutorials%2Fpython-basic%2Fbasic%2F&rx=0&eae=0&fc=384&brdim=0%2C0%2C0%2C0%2C1920%2C0%2C1920%2C1040%2C1920%2C937&vis=1&rsz=%7C%7Cs%7C&abl=NS&fu=8216&bc=31&ifi=8&uci=a!8&btvi=4&fsb=1&xpc=ZuJ21Wg7LZ&p=https%3A//morvanzhou.github.io&dtd=5" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" data-google-container-id="a!8" data-google-query-id="CK31vpCQg-kCFcEgKgodDV0EoQ" data-load-complete="true" style="left: 0px; position: absolute; top: 0px; border: 0px; width: 636px; height: 159px;"></iframe></ins></ins></ins>

string = """
dog runs to cat.
I run to dog.
"""
print(re.search(r"^I", string))                 # None
print(re.search(r"^I", string, flags=re.M))     # <_sre.SRE_Match object; span=(18, 19), match='I'>

重复匹配

如果我们想让某个规律被重复使用, 在正则里面也是可以实现的, 而且实现的方式还有很多. 具体可以分为这三种:

举例如下:

# * : occur 0 or more times
print(re.search(r"ab*", "a"))             # <_sre.SRE_Match object; span=(0, 1), match='a'>
print(re.search(r"ab*", "abbbbb"))        # <_sre.SRE_Match object; span=(0, 6), match='abbbbb'>

# + : occur 1 or more times
print(re.search(r"ab+", "a"))             # None
print(re.search(r"ab+", "abbbbb"))        # <_sre.SRE_Match object; span=(0, 6), match='abbbbb'>

# {n, m} : occur n to m times
print(re.search(r"ab{2,10}", "a"))        # None
print(re.search(r"ab{2,10}", "abbbbb"))   # <_sre.SRE_Match object; span=(0, 6), match='abbbbb'>

分组

我们甚至可以为找到的内容分组, 使用 () 能轻松实现这件事. 通过分组, 我们能轻松定位所找到的内容. 比如在这个 (\d+) 组里, 需要找到的是一些数字, 在 (.+) 这个组里, 我们会找到 “Date: “ 后面的所有内容. 当使用 match.group() 时, 他会返回所有组里的内容, 而如果给 .group(2) 里加一个数, 它就能定位你需要返回哪个组里的信息.

match = re.search(r"(\d+), Date: (.+)", "ID: 021523, Date: Feb/12/2017")
print(match.group())                   # 021523, Date: Feb/12/2017
print(match.group(1))                  # 021523
print(match.group(2))                  # Date: Feb/12/2017

有时候, 组会很多, 光用数字可能比较难找到自己想要的组, 这时候, 如果有一个名字当做索引, 会是一件很容易的事. 我们字需要在括号的开头写上这样的形式 ?P<名字> 就给这个组定义了一个名字. 然后就能用这个名字找到这个组的内容.

match = re.search(r"(?P<id>\d+), Date: (?P<date>.+)", "ID: 021523, Date: Feb/12/2017")
print(match.group('id'))                # 021523
print(match.group('date'))              # Date: Feb/12/2017

<ins class="adsbygoogle" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-4601203457616636" data-ad-slot="3397817325" data-adsbygoogle-status="done" data-overlap-observer-io="false" style="display: block; text-align: center; height: 123px; width: 636px;"><ins id="aswift_4_expand" style="display: inline-table; border: none; height: 123px; margin: 0px; padding: 0px; position: relative; visibility: visible; width: 636px; background-color: transparent;"><ins id="aswift_4_anchor" style="display: block; border: none; height: 123px; margin: 0px; padding: 0px; position: relative; visibility: visible; width: 636px; background-color: transparent; overflow: hidden;"><iframe id="aswift_4" name="aswift_4" sandbox="allow-forms allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" width="636" height="123" frameborder="0" src="https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-4601203457616636&output=html&h=159&slotname=3397817325&adk=3401585631&adf=2619620792&w=636&fwrn=4&lmt=1583377291&rafmt=11&psa=0&guci=2.2.0.0.2.2.0.0&format=636x159&url=https%3A%2F%2Fmorvanzhou.github.io%2Ftutorials%2Fpython-basic%2Fbasic%2F13-10-regular-expression%2F&flash=0&wgl=1&adsid=NT&dt=1587802197991&bpp=2&bdt=393&idt=131&shv=r20200422&cbv=r20190131&ptt=9&saldr=aa&abxe=1&prev_fmts=700x90%2C250x250%2C636x159%2C636x159%2C300x250%2C0x0%2C636x159&nras=2&correlator=3466323590182&frm=20&pv=1&ga_vid=1212726724.1583946939&ga_sid=1587802198&ga_hid=1016610859&ga_fc=0&iag=0&icsg=43490454184&dssz=33&mdo=0&mso=0&rplot=4&u_tz=480&u_his=9&u_java=0&u_h=1080&u_w=1920&u_ah=1040&u_aw=1920&u_cd=24&u_nplug=3&u_nmime=4&adx=484&ady=6053&biw=1903&bih=937&scr_x=0&scr_y=2305&eid=21065214&oid=3&psts=AKB7eCK4lOp292lEAVSqA7mQs41q8NeRpyYvav9UdXDUuHhp_SKIMiPoxfCs2yoHVOjnLQ%2CAKB7eCK4lOp292lEAVSqA7mQs41q8NeRpyYvav9UdXDUuHhp_SKIMiPoxfCs2yoHVOjnLQ%2CAKB7eCK4lOp292lEAVSqA7mQs41q8NeRpyYvav9UdXDUuHhp_SKIMiPoxfCs2yoHVOjnLQ%2CAKB7eCK4lOp292lEAVSqA7mQs41q8NeRpyYvav9UdXDUuHhp_SKIMiPoxfCs2yoHVOjnLQ%2CAKB7eCK4lOp292lEAVSqA7mQs41q8NeRpyYvav9UdXDUuHhp_SKIMiPoxfCs2yoHVOjnLQ%2CAKB7eCK4lOp292lEAVSqA7mQs41q8NeRpyYvav9UdXDUuHhp_SKIMiPoxfCs2yoHVOjnLQ%2CAKB7eCK4lOp292lEAVSqA7mQs41q8NeRpyYvav9UdXDUuHhp_SKIMiPoxfCs2yoHVOjnLQ&pvsid=322963587975057&pem=821&ref=https%3A%2F%2Fmorvanzhou.github.io%2Ftutorials%2Fpython-basic%2Fbasic%2F&rx=0&eae=0&fc=896&brdim=0%2C0%2C0%2C0%2C1920%2C0%2C1920%2C1040%2C1920%2C937&vis=1&rsz=%7C%7CeEbr%7C&abl=CS&pfx=0&fu=8344&bc=31&ifi=5&uci=a!5&btvi=5&fsb=1&xpc=6Rn7ABKl1J&p=https%3A//morvanzhou.github.io&dtd=M" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" data-google-container-id="a!5" data-google-query-id="CK-2rcSQg-kCFYrXuwgdepIJ3w" data-load-complete="true" style="left: 0px; position: absolute; top: 0px; border: 0px; width: 636px; height: 123px;"></iframe></ins></ins></ins>

findall

前面我们说的都是只找到了最开始匹配上的一项而已, 如果需要找到全部的匹配项, 我们可以使用 findall 功能. 然后返回一个列表. 注意下面还有一个新的知识点, | 是 or 的意思, 要不是前者要不是后者.

# findall
print(re.findall(r"r[ua]n", "run ran ren"))    # ['run', 'ran']

# | : or
print(re.findall(r"(run|ran)", "run ran ren")) # ['run', 'ran']

replace

我们还能通过正则表达式匹配上一些形式的字符串然后再替代掉这些字符串. 使用这种匹配 re.sub(), 将会比 python 自带的 string.replace() 要灵活多变.

print(re.sub(r"r[au]ns", "catches", "dog runs to cat"))     # dog catches to cat

split

再来我们 Python 中有个字符串的分割功能, 比如想获取一句话中所有的单词. 比如 "a is b".split(" "), 这样它就会产生一个列表来保存所有单词. 但是在正则中, 这种普通的分割也可以做的淋漓精致.

print(re.split(r"[,;\.]", "a;b,c.d;e"))             # ['a', 'b', 'c', 'd', 'e']

compile

最后, 我们还能使用 compile 过后的正则, 来对这个正则重复使用. 先将正则 compile 进一个变量, 比如 compiled_re, 然后直接使用这个 compiled_re 来搜索.

compiled_re = re.compile(r"r[ua]n")
print(compiled_re.search("dog ran to cat"))  # <_sre.SRE_Match object; span=(4, 7), match='ran'>

小抄

为了大家方便记忆, 我很久以前在网上找到了一份小抄, 这个小抄的原出处应该是这里. 小抄很有用, 不记得的时候回头方便看.


RegEx.png
上一篇下一篇

猜你喜欢

热点阅读