首页 > 解决方案 > 给定带有变量的字符串模式,如何使用python匹配和查找变量字符串?

问题描述

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

给定上面的模式和文本,我如何生成一个函数,它将模式作为第一个参数,文本作为第二个参数并输出单词“this”?

例如。

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

标签: pythonregexmatching

解决方案


您可以使用此函数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.

代码演示


推荐阅读