【问题标题】:How do I ignore the group in a regex split in python? [duplicate]如何在 python 的正则表达式拆分中忽略组? [复制]
【发布时间】:2016-10-07 14:24:17
【问题描述】:

我知道这可能是一个非常简单的问题,但我正在努力在 python 中拆分一个字符串。我的正则表达式有这样的组分隔符:

myRegex = "(\W+)"

我想把这个字符串解析成单词:

testString = "This is my test string, hopefully I can get the word i need"
testAgain = re.split("(\W+)", testString)

结果如下:

['This', ' ', 'is', ' ', 'my', ' ', 'test', ' ', 'string', ', ', 'hopefully', ' ', 'I', ' ', 'can', ' ', 'get', ' ', 'the', ' ', 'word', ' ', 'i', ' ', 'need']

这不是我所期望的。我希望该列表包含:

['This','is','my','test']......etc

现在我知道这与我的正则表达式中的分组有关,我可以通过删除括号来解决这个问题。 但是我怎样才能保留括号并得到上面的结果呢?

抱歉这个问题,我已经阅读了关于 regex spliting with groups 的官方 python 文档,但我仍然不明白为什么我的列表中有空格

【问题讨论】:

  • 为什么要保留这些括号(捕获组)?
  • 你的意思是你还想使用捕获组?试试myRegex = r"\s*([^\w\s])\s*"

标签: python regex


【解决方案1】:

如本答案How to split but ignore separators in quoted strings, in python? 中所述,您可以在数组拆分后简单地对其进行切片。这样做很容易,因为您想要所有其他成员,从第一个成员开始(所以 1,3,5,7)

您可以使用如下所述的 [start:end:step] 表示法:

testString = "This is my test string, hopefully I can get the word i need"
testAgain = re.split("(\W+)", testString)
testAgain = testAgain[0::2]

另外,我必须指出\W 匹配任何非单词字符,包括标点符号。如果您想保留标点符号,则需要更改您的正则表达式。

【讨论】:

  • 是的,这就是我要找的。谢谢!
【解决方案2】:

你可以这样做:

testAgain = testString.split()  # built-in split with space

不同的regex 方法:

testAgain = re.split(r"\s+", testString)   # split with space
testAgain = re.findall(r"\w+", testString) # find all words
testAgain = re.findall(r"\S+", testString) # find all non space characters

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 2018-10-30
    • 1970-01-01
    • 2014-08-05
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2022-12-15
    相关资源
    最近更新 更多