账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    正则怎么匹配结尾的换行符呢?
    • 2019-06-13 00:00
    • 11
    33
    0
    需要匹配的字符串:
    http {
      server {
        key5;
        key0 value0;
        key9;
      }
      server {
        key7 value7;
      }
      key3;
    }
    double = r'\s*"[^"]*"'
    single = r'\s*\'[^\']*\''
    normal = r'\s*[^;\s]*'
    s1 = r'{}|{}|{}'.format(double, single, normal)
    s = r'^\s*({})\s*((?:{})+);'.format(s1, s1)
    m = re.compile(s, re.S).search(data[index:])
    if m:
        print '>>>', m.group(1), m.group(2)

    如果s变量用分号作为结尾匹配则可以成功,结果为

    >>> key5 
    >>> key0 value0
    >>> key9 
    >>> key7 value7
    >>> key3 

    但是如果原配置文件结果不是分号,而是仅仅是一个换行的话,为什么用以下s变量则匹配失败呢?

    s = r'^\s*({})\s*((?:{})+)\n'.format(s1, s1)

    输出结果却为:

    >>> key5 key0 value0
        key9
      }
      server {
        key7 value7
      }
      key3
    1
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 給理想一點時間。 普通会员 1楼

      在正则表达式中,你不能直接匹配换行符。换行符在字符串中并不是一个字符,而是由\n(一个新行符)和\r(一个回车符)组成的。因此,你不能使用/\r来匹配换行符。

      但是,如果你想要在字符串的末尾添加一个换行符,你可以使用\n\r的组合,或者使用\r\n来表示两个换行符。例如:

      python s = "Hello\nWorld\r\n" print(s) # 输出 "Hello\nWorld"

      或者

      python s = "Hello\nWorld\r\n" print(s + "\r") # 输出 "Hello\nWorld\r\n"

      如果你想要在字符串的末尾添加两个换行符,你可以使用\n\r\n的组合,或者使用\r\n来表示两个换行符。例如:

      python s = "Hello\nWorld\r\n" print(s + "\r\n") # 输出 "Hello\nWorld\r\n"

      或者

      python s = "Hello\nWorld\r\n" print(s + "\r\n\n") # 输出 "Hello\nWorld\n"

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部