-->

正则表达式 - 一个字的缩写匹配(Regex - Matching Abbreviations of

2019-10-19 05:03发布

我想提供以下的正则表达式作为回答这个问题 ,但我似乎不能写的正则表达式我一直在寻找:

w?o?r?d?p?r?e?s?s?

这应该与这个词的缩写有序wordpress ,但它也可以在所有符合什么。

如何修改上述正则表达式,以便它, 以便匹配至少4个字符 ? 喜欢:

  • wrdp
  • wordp
  • wpress
  • WordPress的

我想知道什么是做到这一点的最好办法... =)

Answer 1:

你可以使用一个前向断言:

^(?=.{4})w?o?r?d?p?r?e?s?s?$


Answer 2:

什么PHP的相似性检查的功能呢?

  • 莱文斯坦
  • similar_text


Answer 3:

if ( strlen($string) >= 4 && preg_match('#^w?o?r?d?p?r?e?s?s?$#', $string) ) {
    // abbreviation ok
}

除非该字符串为至少4个字符长这甚至不会运行正则表达式。



Answer 4:

我知道这是不是一个正则表达式,只是为了好玩...

#!/usr/bin/python

FULLWORD = "wordprocess"

def check_word(word):
    i, j = 0, 0
    while i < len(word) and j < len(FULLWORD):
        if word[i] == FULLWORD[j]:
            i += 1; j += 1
        else:
            j += 1

    if j >= len(FULLWORD) or i < 4 or i >= len(FULLWORD):
        return "%s: FAIL" % word
    return "%s: SUCC" % word

print check_word("wd")
print check_word("wdps")
print check_word("wsdp")
print check_word("wordprocessr")


文章来源: Regex - Matching Abbreviations of a Word