【问题标题】:Using regular expressions on a list that has been converted to a string在已转换为字符串的列表上使用正则表达式
【发布时间】:2015-06-17 18:51:40
【问题描述】:

取以下代码:

>>>foo = ['abcdefgdfsrf1\tword\tfdsaerg32543','2343221d2\tfds\tss']
>>>print re.findall('(\d+)\s+(\w+)\s',str(foo))
[]

正则表达式没有正确匹配,因为列表中每个元素周围的单引号干扰了整个字符串的引号匹配。更改此代码以使其匹配的最 Pythonic 方式是什么

1\tword\t

\tfds\t

?

【问题讨论】:

    标签: python regex string list


    【解决方案1】:

    这里的问题是str(foo) 正在创建foo 的表示:

    >>> str(foo)
    "['abcdefgdfsrf1\\tword\\tfdsaerg32543', '2343221d2\\tfds\\tss']"
    

    所以它会转义'\t',而你想要文字值。

    要么加入(带空格):

    >>> re.findall('(\d+)\s+(\w+)\s',' '.join(foo))
    [('1', 'word'), ('32543', '2343221d2')]
    

    或加入非空格字符:

    >>> re.findall('(\d+)\s+(\w+)\s','x'.join(foo))
    [('1', 'word'), ('2', 'fds')]
    

    或迭代:

    >>> [re.findall('(\d+)\s+(\w+)\s', str) for str in foo]
    [[('1', 'word')], [('2', 'fds')]]
    

    【讨论】:

      【解决方案2】:

      你可以只使用列表推导式吗?

      >>> [re.findall('(\d+)\s+(\w+)\s', f) for f in foo]
      [[('1', 'word')], [('2', 'fds')]]
      

      【讨论】:

        猜你喜欢
        • 2018-08-14
        • 2021-08-05
        • 2019-06-23
        • 2021-09-16
        • 1970-01-01
        • 2012-01-28
        • 2022-11-18
        • 1970-01-01
        • 2018-12-30
        相关资源
        最近更新 更多