用正则表达式匹配Python单词

2024-09-28 23:40:05 发布

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

我正在寻找一个正则表达式匹配的话,其中头两个字母等于最后两个字母。一个例子可以阐明需求。你知道吗

给出以下文本:

The dodo was one of the sturdiest birds. An educated termite may learn how to operate a phonograph, but it's unlikely. I sense that an amalgam that includes magma will enlighten Papa.

如何获得此输出:

answer = [('dodo', 'do'), ('sturdiest', 'st'), ('educated', 'ed'),
          ('termite', 'te'), ('phonograph', 'ph'),
          ('sense', 'se'), ('amalgam', 'am'), ('magma', 'ma'),
          ('enlighten', 'en')]

如您所见,这两个初始字符与最后两个相同。你知道吗

我的想法是过滤任何长度为4个字符或更多的单词,并且单词的前2个字符与后2个匹配。你知道吗

到目前为止,我的字是4个或更多的字符。你知道吗

[A-Za-z]{4,}

我不需要一个完整的程序,我只需要正则表达式。你知道吗


Tags: that字母字符单词例子sense个字符magma
2条回答

the answer of karthik manchala提供的正则表达式上使用一个变量,并注意到您需要与问题中给出的相同的输出,这是一个完整的代码示例:

import re

inputText = """The dodo was one of the sturdiest birds.
An educated termite may learn how to operate a phonograph,
but it's unlikely. I sense that an amalgam that includes
magma will enlighten Papa."""

regex = re.compile(r"((\w{2})\w*\2)")
answer = regex.findall(inputText) 
print("answer = {}".format(answer))

请注意,除了捕获前两个字符的组(\w{2})、允许中间任意数量的字符\w*、最后匹配末尾的第一个组\2,我还用另一组括号( ... )包围了整个regexp。你知道吗

运行此命令时,整个单词将是\1,而双字符组是\2,使用findall将查找所有出现的情况并返回元组列表,其中每个元组都是捕获组。你知道吗

可以使用以下正则表达式:

(\w{2})\w*\1

说明:

  • (\w{2}):匹配任意两个字母并将它们放入捕获组1( )
  • \w*:匹配零个或多个字母
  • \1:精确匹配第一组括号中捕获的两个字母

Regex DEMO

相关问题 更多 >