【问题标题】:Python Regex search + OffsetPython 正则表达式搜索 + 偏移
【发布时间】:2014-12-22 02:58:50
【问题描述】:

我正在尝试搜索一行中的特定字符串,并在该行中的字符串后面打印 10 个字符。

例如:

"Empty user name specified in NTLM authentication. Port=443, Client ip=/10.234.112.164, port=2629. Prompting for auth again."

我想在上面的行中搜索“ip=/”并获取接下来的 15 个字符。 如此有效,我需要“10.234.112.164”值。

我尝试过使用 re.search 和 .end() 索引。我不确定如何进一步获取数据。

【问题讨论】:

  • 欢迎来到 Stack Overflow!您使用的是什么正则表达式模式,它返回什么结果?请将其编辑到您的问题中。

标签: python regex offset


【解决方案1】:

我想你想从'log?'中获取IP地址。如果你想获取IP,如果你在上面的行中搜索“ip=/”并获取接下来的15个字符,肯定会出错,因为IP在'x.x.x.x'和'xxx.xxx.xxx.xxx'之间。例如,如果IP是10.24.12.14,你得到的结果(接下来的15个字符)是'10.24.12.14,po',你想要吗这个?

所以你应该做一些修改:

>>> a = '......in NTLM authentication. Port=443, Client ip=/10.234.112.164, port=2629.'
>>> b = '......in NTLM authentication. Port=443, Client ip=/10.23.12.14, port=2629.29.'
>>> c = '......in NTLM authentication. Port=443, Client ip=/1.3.1.1, port=2629.29.'
>>> d = '......in NTLM authentication. Port=443, Client ip=/110.223.111.211, port=2629.29.'
>>> re.search(r'ip=\/(\d+.\d+.\d+.\d+)', a).group(1)
'10.234.112.164'
>>> re.search(r'ip=\/(\d+.\d+.\d+.\d+)', b).group(1)
'10.23.12.14'
>>> re.search(r'ip=\/(\d+.\d+.\d+.\d+)', c).group(1)
'1.3.1.1'
>>> re.search(r'ip=\/(\d+.\d+.\d+.\d+)', d).group(1)
'110.223.111.211'

【讨论】:

    【解决方案2】:

    你可以使用capturing groups

    ip=\/(.{15})
    

    () 称为捕获组,{} 称为重复量词。所以.{15} 重复前一个标记.匹配除换行符以外的任何字符)正好 15 次。

    代码:

    >>> s = "Empty user name specified in NTLM authentication. Port=443, Client ip=/10.234.112.164, port=2629. Prompting for auth again."
    >>> re.search(r'ip=\/(.{15})', s).group(1)
    '10.234.112.164,'
    

    Positive lookbehind assertion.

    (?<=ip=\/).{15}
    

    (?&lt;=ip=\/) 调用了肯定的lookbehind,它断言匹配必须以字符串 ip=/ 开头。而.{15} 模式正好匹配 15 个字符。

    DEMO

    代码:

    >>> s = "Empty user name specified in NTLM authentication. Port=443, Client ip=/10.234.112.164, port=2629. Prompting for auth again."
    >>> re.search(r'(?<=ip=\/).{15}', s).group()
    '10.234.112.164,'
    

    【讨论】:

      【解决方案3】:

      您可以使用partition 来做到这一点而无需正则表达式:

      >>> s = "Empty user name specified in NTLM authentication. Port=443, Client ip=/10.234.112.164, port=2629. Prompting for auth again."
      >>> s.partition('ip=/')[2].partition(',')[0]
      '10.234.112.164'
      

      这只是获取ip=/之后和以下逗号之前的所有内容,因此ip地址的具体长度或格式是什么(如果没有ip=/,它将返回一个空字符串)。

      【讨论】:

      • 非常感谢 NeoWu 和 Avinash Raj。 NeoWu,你成功了。这正是我想要的!但是我还需要做其他类似的搜索(例如从日志中提取用户名),而 Avinash 的方法将是完美的!
      猜你喜欢
      • 2013-08-16
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 2015-02-23
      • 2015-05-30
      • 2014-01-23
      相关资源
      最近更新 更多