【发布时间】:2019-10-14 07:47:54
【问题描述】:
我有这个字符串
template = "Hello my name is <name>, I'm <age>."
我想测试我的字符串是否与该模板匹配,并且任何东西都可以代替占位符。占位符以 <place holder here> 这样的括号开始和结束。例如这个字符串会匹配
string = "Hello my name is John Doe, I'm 30 years old."
我还想提取替换占位符的部分字符串。对于上面的例子,我想获取列表:
['John Doe', '30 years old']
我可以使用模式<(.*?)> 为正则表达式提取模板的占位符,但我目前仍坚持如何从字符串中提取实际替换。我需要一个通用的方法,我不想硬编码模式以匹配完整的模板,因为我有很多模板要检查。有没有聪明的方法来做到这一点?
【问题讨论】:
标签: python regex regex-lookarounds regex-group