使用正则表达式匹配字符串中的多个单词

时间:2015-05-06 07:22:17

标签: python regex

我使用Python来匹配句子中的几个单词并针对单元测试进行测试。我想要一个匹配所有这些单词的正则表达式,并给我下面提到的这些输出:

firstword = "<p>This is @Timberlake</p>"
outputfirstword = "@Timberlake"

查找以@符号

开头的单词
secondword = "<p>This is @timber.lake</p>"
outputsecondword = "@timber.lake"

单词之间的句点没问题。

thirdword = "This is @Timberlake. Yo!"
outputthirdword = "@Timberlake"

如果句点后有空格,则句号和空格都不计入outputthirdword

fourthword = "This is @Timberlake."
outputfourthword = "@Timberlake"

不包括最后一段时间(。)。

4 个答案:

答案 0 :(得分:2)

使用此正则表达式:

(?i)@[a-z.]+\b

您可以使用捕获组提取所需的部分。 的 Live demo

说明:

(?i)     # Enabling case-insensitive modifier
@        # Literal @
[a-z.]   # Match letters a to z as well as a period
\b       # Ending at a word boundary

答案 1 :(得分:1)

@[a-zA-Z]+\b(?:\.[a-zA-Z]+\b)?

您可以使用此功能。See demo.

import re
p = re.compile(r'@[a-zA-Z]+\b(?:\.[a-zA-Z]+\b)?')
test_str = "This is @Timberlake. Yo!\n<p>This is @timber.lake</p>"

re.findall(p, test_str)

答案 2 :(得分:0)

一种方法是使用以下正则表达式并使用点删除结果:

@[a-zA-Z.]+

例如,如果您使用re.search,则可以执行以下操作:

re.search(r'@[a-zA-Z.]+','my_string').group(0).strip('.')

您可以使用以下不需要strip的正则表达式:

@[a-zA-Z]+.?[a-zA-Z]+

Demo

答案 3 :(得分:0)

正如@Kasra所说,正则表达式很好用。 但它最终不会删除点。

使用下面的正则表达式,我相信这是你所期望的。

@[a-zA-Z.]+[a-zA-Z]+

请参阅下面的示例,它不在Python中,但正则表达式应该是相同的。

$ (echo "<p>This is @Timberlake</p>"; echo "<p>This is @timber.lake</p>"; echo "This is @Timberlake."; echo "<p>This is @tim.ber.lake</p>") | grep -Eo '@[a-zA-Z.]+[a-zA-Z]+'
@Timberlake
@timber.lake
@Timberlake
@tim.ber.lake