如何使用正则表达式查找以冒号(:)结尾的所有单词

2024-09-28 21:26:38 发布

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

我不熟悉正则表达式,我有以下表达式,我想使用正则表达式查找以冒号(:)结尾的单词或连续单词

Incarcerate: imprison or confine, Strike down: if someone is struck down, especially by an illness, they are killed or severely harmed by it, Accost: approach and address.

输出应该是这样的Incarcerate:, Strike down:, Accost:。我已经编写了以下正则表达式,但它捕获了以下内容

我的正则表达式->(\w+):+

它捕获像Incarcerate:, Accost:这样的单词,但不捕获Strike down: 请帮帮我

我想用typescript和python两种语言来实现它


Tags: orbyifis表达式结尾单词down
1条回答
网友
1楼 · 发布于 2024-09-28 21:26:38

您可以选择重复空格和1+字字符。注意,单词在组1中,:在组外

(\w+(?: \w+)*):

Regex demo

要在匹配中包括:,请执行以下操作:

\w+(?: \w+)*:

模式匹配

  • \w+匹配一个或多个单词字符
  • (?: \w+)*匹配空格和1+个单词字符重复0+次
  • :匹配单个:

Regex demo

Python中的示例

import re
s = "Incarcerate: imprison or confine, Strike down: if someone is struck down, especially by an illness, they are killed or severely harmed by it, Accost: approach and address."
pattern = r"\w+(?: \w+)*:"
 
print(re.findall(pattern, s))

输出

['Incarcerate:', 'Strike down:', 'Accost:']

相关问题 更多 >