Python正则表达式Regular Expression初探

这篇具有很好参考价值的文章主要介绍了Python正则表达式Regular Expression初探。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Python正则表达式Regular Expression初探,Python,python,regex,正则表达式

目录

Regular

匹配规则

单字符匹配

 数量匹配

边界匹配

 分组匹配

贪婪与懒惰

原版说明

特殊字符

转义序列

模块方法

函数说明

匹配模式

常用匹配规则

1. 匹配出所有整数

2. 匹配11位且13开头的整数


Regular

Python的re模块提供了完整的正则表达式功能。正则表达式(Regular Expression)是一种强大的文本模式匹配工具,它能高效地进行查找、替换、分割等复杂字符串操作。

在Python中,通过 import re 即可引入这一神器。

匹配规则

单字符匹配

语法 功能 注意事项
. 匹配除换行符(\n)以外,任意一个字符。 \.匹配点本身
[] 匹配[]中列举的字符,可以是很多单个,也可以范围 范围写法例如[2-6],[“a”-”b”]
\d 匹配数字,即0-9  
\D 匹配非数字  
\s 匹配空白,即空格、tab键  
\S 匹配非空白  
\w 匹配单词字符,即a-z,A-Z,0-9,_  
\W 匹配非单词字符  

 数量匹配

语法 功能 注意事项
* 匹配前一个规则的字符出现0至无数次  
+ 匹配前一个规则的字符出现1至无数次  
匹配前一个规则的字符出现0次或1次  
{n} 匹配前一个规则的字符出现n次  
{n,} 匹配前一个规则的字符出现最少n次  
{m,n} 匹配前一个规则的字符出现m到n次  

边界匹配

语法 功能 注意事项
^ 匹配字符串的开始 放在子表达式前
$ 匹配字符串的结束 放在子表达式后
\b 匹配单词的开始或结束  
\B 匹配不是单词开头或结束的位置  

 分组匹配

语法 功能 注意事项
| 匹配左右任意一个表达式  
() 将匹配的内容里一部分抠出来就用括号 抠出的内容不止一个就放到元组里

贪婪与懒惰

语法 功能 注意事项
*? 重复任意次 尽可能少重复
+? 重复1次或更多次 尽可能少重复
?? 重复0次或一次 尽可能少重复
{n,m}? 重复nm 尽可能少重复
{n,}? 重复n次以上 尽可能少重复

原版说明

特殊字符

    The special characters are:
        "."      Matches any character except a newline.
        "^"      Matches the start of the string.
        "$"      Matches the end of the string or just before the newline at
                 the end of the string.
        "*"      Matches 0 or more (greedy) repetitions of the preceding RE.
                 Greedy means that it will match as many repetitions as possible.
        "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
        "?"      Matches 0 or 1 (greedy) of the preceding RE.
        *?,+?,?? Non-greedy versions of the previous three special characters.
        {m,n}    Matches from m to n repetitions of the preceding RE.
        {m,n}?   Non-greedy version of the above.
        "\\"     Either escapes special characters or signals a special sequence.
        []       Indicates a set of characters.
                 A "^" as the first character indicates a complementing set.
        "|"      A|B, creates an RE that will match either A or B.
        (...)    Matches the RE inside the parentheses.
                 The contents can be retrieved or matched later in the string.
        (?aiLmsux) The letters set the corresponding flags defined below.
        (?:...)  Non-grouping version of regular parentheses.
        (?P<name>...) The substring matched by the group is accessible by name.
        (?P=name)     Matches the text matched earlier by the group named name.
        (?#...)  A comment; ignored.
        (?=...)  Matches if ... matches next, but doesn't consume the string.
        (?!...)  Matches if ... doesn't match next.
        (?<=...) Matches if preceded by ... (must be fixed length).
        (?<!...) Matches if not preceded by ... (must be fixed length).
        (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
                           the (optional) no pattern otherwise.

转义序列

    The special sequences consist of "\\" and a character from the list
    below.  If the ordinary character is not on the list, then the
    resulting RE will match the second character.
        \number  Matches the contents of the group of the same number.
        \A       Matches only at the start of the string.
        \Z       Matches only at the end of the string.
        \b       Matches the empty string, but only at the start or end of a word.
        \B       Matches the empty string, but not at the start or end of a word.
        \d       Matches any decimal digit; equivalent to the set [0-9] in
                 bytes patterns or string patterns with the ASCII flag.
                 In string patterns without the ASCII flag, it will match the whole
                 range of Unicode digits.
        \D       Matches any non-digit character; equivalent to [^\d].
        \s       Matches any whitespace character; equivalent to [ \t\n\r\f\v] in
                 bytes patterns or string patterns with the ASCII flag.
                 In string patterns without the ASCII flag, it will match the whole
                 range of Unicode whitespace characters.
        \S       Matches any non-whitespace character; equivalent to [^\s].
        \w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]
                 in bytes patterns or string patterns with the ASCII flag.
                 In string patterns without the ASCII flag, it will match the
                 range of Unicode alphanumeric characters (letters plus digits
                 plus underscore).
                 With LOCALE, it will match the set [0-9_] plus characters defined
                 as letters for the current locale.
        \W       Matches the complement of \w.
        \\       Matches a literal backslash.

模块方法

    This module exports the following functions:
        match     Match a regular expression pattern to the beginning of a string.
        fullmatch Match a regular expression pattern to all of a string.
        search    Search a string for the presence of a pattern.
        sub       Substitute occurrences of a pattern found in a string.
        subn      Same as sub, but also return the number of substitutions made.
        split     Split a string by the occurrences of a pattern.
        findall   Find all occurrences of a pattern in a string.
        finditer  Return an iterator yielding a Match object for each match.
        compile   Compile a pattern into a Pattern object.
        purge     Clear the regular expression cache.
        escape    Backslash all non-alphanumerics in a string.

函数说明

match(pattern, string, flags=0)
    Try to apply the pattern at the start of the string, returning
    a Match object, or None if no match was found.

fullmatch(pattern, string, flags=0)
    Try to apply the pattern to all of the string, returning
    a Match object, or None if no match was found.

search(pattern, string, flags=0)
    Scan through string looking for a match to the pattern, returning
    a Match object, or None if no match was found.

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the Match object and must return
    a replacement string to be used.

subn(pattern, repl, string, count=0, flags=0)
    Return a 2-tuple containing (new_string, number).
    new_string is the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in the source
    string by the replacement repl.  number is the number of
    substitutions that were made. repl can be either a string or a
    callable; if a string, backslash escapes in it are processed.
    If it is a callable, it's passed the Match object and must
    return a replacement string to be used.

split(pattern, string, maxsplit=0, flags=0)
    Split the source string by the occurrences of the pattern,
    returning a list containing the resulting substrings.  If
    capturing parentheses are used in pattern, then the text of all
    groups in the pattern are also returned as part of the resulting
    list.  If maxsplit is nonzero, at most maxsplit splits occur,
    and the remainder of the string is returned as the final element
    of the list.

findall(pattern, string, flags=0)
    Return a list of all non-overlapping matches in the string.

    If one or more capturing groups are present in the pattern, return
    a list of groups; this will be a list of tuples if the pattern
    has more than one group.

    Empty matches are included in the result.

finditer(pattern, string, flags=0)
    Return an iterator over all non-overlapping matches in the
    string.  For each match, the iterator returns a Match object.

    Empty matches are included in the result.

compile(pattern, flags=0)
    Compile a regular expression pattern, returning a Pattern object.

purge()
    Clear the regular expression caches

escape(pattern)
    Escape special characters in a string.


匹配模式

    Each function other than purge and escape can take an optional 'flags' argument
    consisting of one or more of the following module constants, joined by "|".
    A, L, and U are mutually exclusive.
        A  ASCII       For string patterns, make \w, \W, \b, \B, \d, \D
                       match the corresponding ASCII character categories
                       (rather than the whole Unicode categories, which is the
                       default).
                       For bytes patterns, this flag is the only available
                       behaviour and needn't be specified.
        I  IGNORECASE  Perform case-insensitive matching.
        L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.
        M  MULTILINE   "^" matches the beginning of lines (after a newline)
                       as well as the string.
                       "$" matches the end of lines (before a newline) as well
                       as the end of the string.
        S  DOTALL      "." matches any character at all, including the newline.
        X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.
        U  UNICODE     For compatibility only. Ignored for string patterns (it
                       is the default), and forbidden for bytes patterns.


常用匹配规则

掌握正则的关键是根据规则来编写匹配样式,下面列出一些常用的Regular pattern:

1. 匹配出所有整数

>>> import re
>>> pat = '\d+'
>>> txt = 'No.123;Tel:1396260000'
>>> re.findall(pat, txt)
['123', '1396260000']

2. 匹配11位且13开头的整数

注意r'13\d{9}',13开头余下的9位数字用\d{9}表示

>>> import re
>>> txt = '''
... 001:13962600001
... 002:1330626001
... 003:18962600002
... 004:13106260003
... 005:16605200006
... '''
>>> pat = r'13\d{9}'
>>> re.findall(pat, txt)
['13962600001', '13106260003']

......

素材收集中。。。。。。文章来源地址https://www.toymoban.com/news/detail-814063.html

到了这里,关于Python正则表达式Regular Expression初探的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • ABAP SQL & CDSView Entity中使用正则RegEx表达式(Regular Expressions)

    DEMO_REGEX DEMO_REGEX_TOY SQL函数 语法 作用 执行逻辑 返回类型 CDS   View Entities ABAP   SQL LIKE_REGEXPR LIKE_REGEXPR(            PCRE = pcre,            VALUE = sql_exp1[,            CASE_SENSITIVE = case]) 检查字符串是否包含任何 PCRE命中 检查sql_exp是否包含任何   PCRE命中,是则返

    2024年01月24日
    浏览(30)
  • Python正则表达式之学习正则表达式三步曲

            正则表达式描述了一种字符串匹配的模式,可以用来检查一个串的有无某子串,或者做子串匹配替换,取出子串等操作。也可以说正则表达式就是字符串的匹配规则,也可以理解为是一种模糊匹配,匹配满足正则条件的字符串。         1、数据验证(eg:表单验

    2024年02月15日
    浏览(49)
  • 老夫的正则表达式大成了,桀桀桀桀!!!【Python 正则表达式笔记】

    特殊字符 .^$?+*{}[]()| 为特殊字符,若想要使用字面值,必须使用 进行转义 字符类 [] [] 匹配包含在方括号中的任何字符。它也可以指定范围,例: [a-zA-Z0-9] 表示a到z,A到Z,0到9之间的任何一个字符 [u4e00-u9fa5] 匹配 Unicode 中文 [^x00-xff] 匹配双字节字符(包括中文) 在 [] 中

    2024年02月04日
    浏览(47)
  • 机器学习与数据科学-专题1 Python正则表达式-【正则表达式入门-1】

    为了完成本关任务,你需要掌握: 在 Python 中使用正则表达式; 最基础正则表达式; 正则匹配函数。 在 Python 中使用正则表达式 正可谓人生苦短,我用 Python。Python 有个特点就是库非常多,自然拥有正则匹配这种常见的库,并且此库已经嵌入在 Python 标准库中,使用起来非常

    2024年01月22日
    浏览(39)
  • python正则表达式-正则基础

    目录 一、任一元素 二、匹配特定的字符类别          1、d  w 三、多个元素          1、两位元素 [][]          2、* + ?          3、重复次数 {}          4、位置匹配 ^ $          5、子表达式()         []:1、[ab] 匹配a或b;        2、[0-9] 匹配任意一个数

    2024年02月05日
    浏览(34)
  • PYthon正则表达式

    正则表达式是对字符串(包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为“元字符”))操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串”用来表达对字符串的一种过滤逻辑。正则

    2024年01月17日
    浏览(37)
  • python 正则表达式

    2024年01月17日
    浏览(42)
  • Python正则表达式(小结)

    正则表达式(regular expression,有时简写为RegEx 或 regex)就是用一组由字母和符号组成的“表达式”来描述一个特征,然后去验证另一个“字符串”是否符合/匹配这个特征。 (1)验证字符串是否符合指定特征,比如验证邮件地址是否符合特定要求等; (2)用来查找字符串,

    2024年02月05日
    浏览(29)
  • 速通Python正则表达式

    几乎所有语言中的正则表达式都有相类似的语法,python亦莫能外。 接下来直观地看一下最常用的的三大函数 其中, re.match 要求从头匹配; search 可以从任意位置匹配,但只返回第一个匹配的值的位置; findall 返回所有符合要求的值。 任意字符 . 匹配除了换行符之外的所有字

    2024年02月06日
    浏览(31)
  • Python 正则表达式转义

    这篇文章是关于 Python 正则表达式转义的。 此外,我们将介绍 Python 正则表达式转义以及如何通过适当的示例代码使用它,以及 Python 正则表达式的多种用途。 此外,Python 支持使用正则表达式(或正则表达式)对字符串进行搜索和替换操作。 RegEx 是一种根据预定义模式匹配文

    2024年02月09日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包