正则表达式?匹配部分或整个单词 [英] Regex? Match part of or whole word

查看:56
本文介绍了正则表达式?匹配部分或整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 python 中使用正则表达式来捕获单词或单词的一部分(如果它位于字符串的末尾).

I was wondering if it's possible to use regex with python to capture a word, or a part of the word (if it's at the end of the string).

例如:
目标词 - 马铃薯
字符串 - 这是一个关于土豆的句子"
字符串 - 这是一个关于potat的句子"
字符串 - 这是另一个关于 pota 的句子"

Eg:
target word - potato
string - "this is a sentence about a potato"
string - "this is a sentence about a potat"
string - "this is another sentence about a pota"

谢谢!

推荐答案

import re

def get_matcher(word, minchars):
    reg = '|'.join([word[0:i] for i in range(len(word), minchars - 1, -1)])
    return re.compile('(%s)$' % (reg))

matcher = get_matcher('potato', 4)
for s in ["this is a sentence about a potato", "this is a sentence about a potat", "this is another sentence about a pota"]:
    print matcher.search(s).groups()

输出

('potato',)
('potat',)
('pota',)

这篇关于正则表达式?匹配部分或整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆