Python Regex:同一个单词中每个字母的符号+

时间:2017-10-05 15:10:40

标签: python regex

我正在使用Python。 我想制作一个正则表达式,分别是以下例子:

Day
Dday
Daay
Dayy
Ddaay
Ddayy
...

所以,一个单词的每个字母,一次或多次。 我怎么能轻易写出来?是否存在易于表达的表达方式? 我有很多话。 感谢

4 个答案:

答案 0 :(得分:1)

我们可以尝试使用以下正则表达式模式:

^([A-Za-z])\1*([A-Za-z])\2*([A-Za-z])\3*$

这匹配并捕获一个字母,然后是此字母的任意数量。您在上述模式中看到的\1反向引用,它代表上一个匹配的字母(依据\2\3)。

<强>代码:

word = "DdddddAaaaYyyyy"
matchObj = re.match( r'^([A-Za-z])\1*([A-Za-z])\2*([A-Za-z])\3*$', word, re.M|re.I)

if matchObj:
    print "matchObj.group() : ", matchObj.group()
    print "matchObj.group(1) : ", matchObj.group(1)
    print "matchObj.group(2) : ", matchObj.group(2)
    print "matchObj.group(3) : ", matchObj.group(3)
else:
    print "No match!!"

Demo

答案 1 :(得分:1)

要匹配字符一次或多次,您可以使用+ quantifier。要动态构建完整模式,您需要将单词拆分为字符,并在每个字符后添加+

pattern = "".join(char + "+" for char in word)

然后只是match模式案例不敏感。

演示:

>>> import re
>>> word = "Day"
>>> pattern = "".join(char + "+" for char in word)
>>> pattern
'D+a+y+'
>>> words = ["Dday", "Daay", "Dayy", "Ddaay", "Ddayy"]
>>> all(re.match(pattern, word, re.I) for word in words)
True

答案 2 :(得分:0)

尝试/d+a+y+/gi

  • d+匹配d一次或多次。
  • a+匹配a一次或多次。
  • y+匹配y一次或多次。

答案 3 :(得分:0)

根据我原来的评论,下面的内容与我解释完全相同。

由于您希望能够在很多单词上使用它,我认为这正是您所需要的。

import re

word = "day"

regex = r"^"+("+".join(list(word)))+"+$"

test_str = ("Day\n"
    "Dday\n"
    "Daay\n"
    "Dayy\n"
    "Ddaay\n"
    "Ddayy")

matches = re.finditer(regex, test_str, re.IGNORECASE | re.MULTILINE)

for matchNum, match in enumerate(matches):
    matchNum = matchNum + 1

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

这可以通过将字符串转换为列表,然后将其转换回字符串,将其加到+上并附加相同的字符串来实现。生成的正则表达式将为^d+a+y+$。由于您提供的输入由换行符分隔,因此我添加了re.MULTILINE