python - 给定带有变量的字符串模式,如何使用python匹配和查找变量字符串?
问题描述
pattern = "world! {} "
text = "hello world! this is python"
给定上面的模式和文本,我如何生成一个函数,它将模式作为第一个参数,文本作为第二个参数并输出单词“this”?
例如。
find_variable(pattern, text)
==> 返回 'this' 因为 'this'
解决方案
您可以使用此函数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
.
推荐阅读
- python - Python 中 Beautiful Soup XML 解析的问题
- http-headers - 在响应标头中隐藏 mobilefirst 7 服务器信息
- python - Reading data from /sdb1
- mysql - mysqldump segmentation fault on large --where=(id IN ...)
- r - 根据条件更改日期、月份和时间
- python-3.x - 在条件下删除DataFrame中的元素
- ruby-on-rails - how to create line chart and appear data in rails?
- excel - Remove duplicates from combined data in one cell
- yii2 - yii2 i18n not working with buttons
- node.js - 在 Eclipse 中执行量角器脚本时出现问题