如何组合这两个正则表达式?(带和不带撇号的词)

2024-03-28 23:54:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图构建一个正则表达式来捕获字符串中的每个单词(包括撇号),如下所示:

Despite trying and trying I haven't found a regex to capture all these words

但是我确实希望它忽略像'''这样的词,从words'读取word,从'cause读取cause;也就是说,撇号必须在文本中。你知道吗

我有以下两个表达式:

[a-z]+'[a-z]+
[a-z]+

我假设它们可以由一个简单的运算符连接起来,但我无法找出那个运算符可能是什么。你知道吗


Tags: andto字符串运算符all单词regexcapture
3条回答

这个正则表达式将捕获所有可以选择包含(甚至多个)'的单词,但不能以'开头或结尾

(\w[\w']+\w|\w+)

a demo here

Regular expression visualization

在Python中,您可以使用这个基于交替的regex来匹配所有内部带有单引号的单词并忽略'word1 word2'单词:

s = r"Despite trying and trying I haven't found a regex to capture all these words 'but not capturing these'"

print filter(None, re.findall(r"'[^']*'|(\b\w+(?:'\w+)?\b)", s))
//=> ['Despite', 'trying', 'and', 'trying', 'I', "haven't", 'found', 'a', 'regex', 'to', 'capture', 'all', 'these', 'words']

RegEx Demo

试试这个:

(\w+'\w+)|(\w+)

上面仍然包括words''cause,但没有撇号。你知道吗

相关问题 更多 >