加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

通过NOT使用正则表达式算法和python中的代码进行模式搜索

发布时间:2020-12-14 05:36:01 所属栏目:百科 来源:网络整理
导读:今天我接受了AMD的采访,并被问到一个问题,我不知道如何在没有正则表达式的情况下解决它.这是一个问题: Find all the pattern for the word “Hello” in a text. Consider that there is only ONE char can be in between letters of hello e.g. search for
今天我接受了AMD的采访,并被问到一个问题,我不知道如何在没有正则表达式的情况下解决它.这是一个问题:

Find all the pattern for the word “Hello” in a text. Consider that there is only ONE char can be in between letters of hello e.g. search for all instances of “h.ello”,“hell o”,“he,llo”,or “hel!lo”.

解决方法

既然你也标记了这个问题算法,我只是展示一下我在查看这个问题时会采取的一般方法,而不包括 python的任何语言技巧.

1)我想将字符串拆分为单词列表

2)遍历结果列表中的每个字符串,检查字符串是否匹配’hello’而没有当前索引处的字符(或者它是否匹配’hello’)

3)如果找到匹配,则返回.

这是python中的一个简单方法:

s = "h.ello hello h!ello hell.o none of these"

all = s.split()

def drop_one(s,match):
    if s == match:
        return True # WARNING: Early Return
    for i in range(len(s) - 1):
        if s[:i] + s[i+1:] == match:
            return True

matches = [x for x in all if drop_one(x,"hello")]
print(matches)

此代码段的输出:

['h.ello','hello','h!ello','hell.o']

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读