Python 正则表达式匹配:## ## [英] Python Regular Expression Matching: ## ##

查看:66
本文介绍了Python 正则表达式匹配:## ##的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在逐行搜索文件中是否出现##random_string##.除了多个 #...

I'm searching a file line by line for the occurrence of ##random_string##. It works except for the case of multiple #...

pattern='##(.*?)##'
prog=re.compile(pattern)

string='lala ###hey## there'
result=prog.search(string)

print re.sub(result.group(1), 'FOUND', string)

期望的输出:

"lala #FOUND there"

相反,我得到以下内容,因为它抓住了整个###hey##:

Instead I get the following because its grabbing the whole ###hey##:

"lala FOUND there"

那么我如何忽略开头或结尾的任意数量的#,而只捕获##string##".

So how would I ignore any number of # at the beginning or end, and only capture "##string##".

推荐答案

要在任一端匹配至少两个哈希值:

To match at least two hashes at either end:

pattern='##+(.*?)##+'

这篇关于Python 正则表达式匹配:## ##的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆