给定一个带变量的字符串模式,如何使用python匹配和查找变量字符串?

问题描述 投票:0回答:2
pattern = "world! {} "
text = "hello world! this is python"

鉴于上面的模式和文本,我如何生成一个函数,它将pattern作为第一个参数,text作为第二个参数并输出单词'this'?

例如。

find_variable(pattern, text) ==>返回'this'因为'this'

python regex matching
2个回答
1
投票

您可以使用此函数使用string.format构建具有单个捕获组的正则表达式:

>>> pattern = "world! {} "
>>> text = "hello world! this is python"
>>> def find_variable(pattern, text):
...     return re.findall(pattern.format(r'(\S+)'), text)[0]
...
>>> print (find_variable(pattern, text))

this

PS:你可能想在你的函数中添加一些健全性检查来验证字符串格式和成功的findall

Code Demo


0
投票

不是像anubhava那样的一个班轮,而是使用基本的python知识:

pattern="world!"
text="hello world! this is python"

def find_variabel(pattern,text):
    new_text=text.split(' ')

    for x in range(len(new_text)):
        if new_text[x]==pattern:
            return new_text[x+1]

print (find_variabel(pattern,text))
© www.soinside.com 2019 - 2024. All rights reserved.