zoukankan      html  css  js  c++  java
  • 对一句正则表达式的理解

    在《Python基础教程》的第198页上看到这样一句:

    re.sub(emphasis_pattern, r'<em>\1</em>', 'Hello, *world*!')

    其中:emphasis_pattern = r'\*([^\*]+)\*'

    结果为:'Hello, <em>world</em>!'

    对emphasis_pattern = r'\*([^\*]+)\*'

    头尾的\*取消了元字符*,即只是作为普通字符

    中间的()是一个子模式,字符串中与其匹配的子字符串可以用/1进行模式逆引用

    [ ]+表示[ ]中的字符至少匹配一个

    ^\*表示匹配除了*号外的任何符号

    与其匹配的例子:*abc*   (其中abc可以换成除*的任何字符)

    对re.sub(emphasis_pattern, r'<em>\1</em>', 'Hello, *world*!')

    调用函数sub(pat, repl. string)

    首先要明白string是匹配pat的,函数的作用是将 匹配的部分用字符串repl替换掉:

    如re.sub(r'a[abc]+d' , 'python' , 'hello,abcd')就是:'hello,python'

    所以上面那个奇怪的东东其实就是用<em>\1</em>这个字符串来替换掉'Hello, *world*!'满足emphasis_pattern的部分而已(其实就是*world*)

    那么\1是什么东西?

    查了些资料,发现这个是re里面的子模式的逆向应用

    \1代表的是'Hello, *world*!'匹配emphasis_pattern中( )里面的部分,也就是world

    OK!现在就变成了:

    re.sub( r'\*([^\*]+)\*', '<em>world</em>', 'Hello, *world*!')

    用<em>world</em>替换掉 *world*,搞定

    关于子模式和逆向引用:http://www.cnblogs.com/ylan2009/articles/2382870.html

    通过理解这个正则语句,学到了不少

  • 相关阅读:
    理解jquery的$.extend()、$.fn和$.fn.extend()
    前端跨域请求原理及实践
    [leetcode]Minimum Path Sum
    [leetcode]Jump Game II
    [leetcode]Merge Intervals
    [leetcode]Length of Last Word
    [leetcode]Unique Paths
    [leetcode]Text Justification
    [leetcode]Binary Tree Level Order Traversal
    [leetcode]Jump Game
  • 原文地址:https://www.cnblogs.com/ylan2009/p/2382880.html
Copyright © 2011-2022 走看看