Python 正则表达式:返回包含给定子字符串的单词列表

Vin*_*ent 0 python regex string

什么是f基于正则表达式的函数,给定输入文本和字符串,返回文本中包含该字符串的所有单词。例如:

f("This is just a simple text to test some basic things", "si")
Run Code Online (Sandbox Code Playgroud)

会返回:

["simple", "basic"]
Run Code Online (Sandbox Code Playgroud)

(因为这两个词包含子串"si"

怎么做?

ret*_*oot 5

对于这样的事情,我不会使用正则表达式,我会使用这样的东西:

def f(string, match):
    string_list = string.split()
    match_list = []
    for word in string_list:
        if match in word:
            match_list.append(word)
    return match_list

print f("This is just a simple text to test some basic things", "si")
Run Code Online (Sandbox Code Playgroud)


jed*_*rds 5

我不相信没有比我的方法更好的方法,但类似:

import re

def f(s, pat):
    pat = r'(\w*%s\w*)' % pat       # Not thrilled about this line
    return re.findall(pat, s)


print f("This is just a simple text to test some basic things", "si")
Run Code Online (Sandbox Code Playgroud)

作品:

['simple', 'basic']
Run Code Online (Sandbox Code Playgroud)