gpt4 book ai didi

python - 获取正则表达式不匹配的列表?

转载 作者:太空宇宙 更新时间:2023-11-03 13:03:31 25 4
gpt4 key购买 nike

我正在使用“Python strings split with multiple separators”拆分字符串:

import re
DATA = "Hey, you - what are you doing here!?"
print re.findall(r'\w+', DATA)
# Prints ['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']

我想获得一个单独的列表,其中包含匹配词之间的内容:

[", ", " - ", " ", " ", " ", " ", "!?"]

我该怎么做?

最佳答案

print re.findall(r'\W+', DATA)  # note, UPPER-case "W"

生成您要查找的列表:

[', ', ' - ', ' ', ' ', ' ', ' ', '!?']

我使用了 \W+ 而不是 \w+ 这否定了您使用的字符类。

   \w  Matches word characters, i.e., letters, digits, and underscores.
\W Matches non-word characters, i.e., the negated version of \w

Regular Expression Reference Sheet可能有助于为您的正则表达式搜索/匹配选择最佳字符类/元字符。另外,请参阅此 tutorial了解更多信息(尤其是页面底部的引用部分)

关于python - 获取正则表达式不匹配的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11550763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com