如何使用正则表达式查找以冒号 (:) 结尾的所有单词
How to find all words that ends with colon (:) using regex
我是正则表达式的新手,我有以下表达式,我想使用正则表达式查找以冒号 (:) 结尾的单词或连续单词。
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 中都这样做。
您可以选择重复 space 和 1+ 个单词字符。请注意,单词在组 1 中,:
在组外。
(\w+(?: \w+)*):
要在匹配中包含 :
:
\w+(?: \w+)*:
模式匹配
\w+
匹配1个或多个单词字符
(?: \w+)*
重复 0+ 次匹配一个 space 和 1+ 个单词字符
:
匹配单个:
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:']
我是正则表达式的新手,我有以下表达式,我想使用正则表达式查找以冒号 (:) 结尾的单词或连续单词。
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 中都这样做。
您可以选择重复 space 和 1+ 个单词字符。请注意,单词在组 1 中,:
在组外。
(\w+(?: \w+)*):
要在匹配中包含 :
:
\w+(?: \w+)*:
模式匹配
\w+
匹配1个或多个单词字符(?: \w+)*
重复 0+ 次匹配一个 space 和 1+ 个单词字符:
匹配单个:
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:']