繁体   English   中英

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

[英]Matching multiple words within a string with regular expression

我正在使用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"

不包括最后一个句号(。)。

使用此正则表达式:

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

您可以通过使用捕获组来提取所需的部分。 现场演示

说明:

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

您可以使用它。 参见演示。

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)

一种方法是使用以下正则表达式并用dot剥离结果:

@[a-zA-Z.]+

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

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

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

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

演示

正如@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM