【问题标题】:How to match this kind of string in Python use re?如何在 Python 中使用 re 匹配这种字符串?
【发布时间】:2014-02-24 15:55:33
【问题描述】:

我有几个这样的字符串:

unicode 0, <runtime error >,0
unicode 0, <TLOSS error>
unicode 0, <- Attempt to use MSIL code >
unicode 0, <ModuleNameA>

我正在尝试使用 re 来匹配 "" 中的所有字符串

我试过这个:

items = line.split()
pattern = r"<.+?>"
match = re.findall(pattern, items[2])

但是空间好像不能处理..

谁能帮帮我?

谢谢!

【问题讨论】:

    标签: python regex string-matching


    【解决方案1】:

    items[2] 包含部分内容:

    >>> items = line.split()
    >>> items[2]
    '<runtime'
    

    只需将line 传递给re.findall

    >>> line = 'unicode 0, <runtime error >,0'
    >>> re.findall(r'<.+?>', line)
    ['<runtime error >']
    

    【讨论】:

      【解决方案2】:

      只是不要拆分它们并按原样使用字符串,就像这样

      line = "unicode 0, <runtime error >,0"
      import re
      print(re.findall(r"<.+?>", line))
      # ['<runtime error >']
      

      如果你只想要其中的字符串,你可以这样做

      print(re.search(r"<(.+?)>", line).group(1))
      # runtime error 
      

      【讨论】:

        猜你喜欢
        • 2010-12-07
        • 1970-01-01
        • 2013-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-29
        相关资源
        最近更新 更多