简体   繁体   English

从python中的字符串中使用正则表达式提取括号

[英]Extracting brackets with regex from a string in python

How I can extract {{template|{{template2}}|other params}} from this string if we just know "template": 如果我们只知道“模板”,如何从此字符串中提取{{template | {{template2}} |其他params}}:

{{template0}}
{{template|{{template2}}|other params}}
{{template3}}

This should do what you want: 这应该做你想要的:

>>> match = re.search(r'^{{template\b.*$', your_string, re.M)
>>> match.group()
'{{template|{{template2}}|other params}}'

It uses a word boundary ( \\b ) after 'template' so it will not match 'template0' or 'template3'. 它在'template'之后使用单词边界( \\b ),因此它不匹配'template0'或'template3'。 The re.M option is used so ^ and $ will match the beginnings and ends of lines, instead of the beginning and end of the string. 使用re.M选项,因此^$将匹配行的开头和结尾,而不是字符串的开头和结尾。

Edit: Try the following regex for the newline case from your comment: 编辑:从评论中为新行案例尝试以下正则表达式:

r'^{{template\b(?:[^}]\n+|\n+[^{]|.)*$'

This should work whether you put the newline before or after the | 无论你在|之前还是之后放置换行符,这都应该有效 .

Edit 2: It is very important with regex questions that you specify what the input can look like up front. 编辑2:这是您指定的输入可以是什么样子了前面正则表达式的问题非常重要。 Here is another version that works with the text from your latest comment: 这是另一个版本,与您最新评论中的文本一起使用:

r'^{{template\b(?:[^}\n]\n+|\n+[^{\n]|.)*}}$'

Now it will handle multiple newlines correctly, and I added the }} at the end in case your match is the last bracketed group before lines with other formats. 现在它将正确处理多个换行符,并且我最后添加了}} ,以防你的匹配是带有其他格式的行之前的最后一个括号内组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM