[英]Python: Regex match or condition?
I have a string like {string}{string}{string}
which I'm able to parse by 我有一个像
{string}{string}{string}
这样的{string}{string}{string}
,我可以通过它来解析
import re
input_string = '{string}{string}{string}'
for match in re.finditer(r'{([^}]*)}', input_string):
print str(match.group(0)) #outputs {string}
but I also want to catch strings with an asterick following a curly bracket. 但是我也想在花括号后用星号捕获字符串。
input_string = '{string}{string}*{string}{string}*'
How do I modify the regex so that both {string}
and {string}*
will be caught? 如何修改正则表达式,以便同时捕获
{string}
和{string}*
?
I tried doing r'{([^}]*)}|*'
but doesn't seem to be working. 我尝试做
r'{([^}]*)}|*'
但似乎没有用。
Also, what if a string contains curly brackets? 另外,如果字符串包含大括号怎么办? ex.
恩。
{string{3}}
How do I make sure only the outer {} is caught and not the one's inside? {string{3}}
如何确保仅抓住外部{}而没有抓住内部{}?
Add \\*?
加上
\\*?
at the end of your regex to match an optional *
. 在正则表达式的末尾,以匹配可选的
*
。
import re
input_string = '{string}{string}*{string}{string}*'
for match in re.finditer(r'{([^}]*)}\*?', input_string):
print str(match.group(0)) #outputs {string}
Output: 输出:
{string}
{string}*
{string}
{string}*
As for nested brackets, simple regular expressions cannot parse that. 至于嵌套方括号,简单的正则表达式无法对其进行解析。 You can use recursive regular expressions for this, but it becomes unreadable ( example ).
您可以为此使用递归正则表达式,但是它变得不可读( 示例 )。 You should use a proper parsing library, more discussion and examples here .
您应该在此处使用适当的解析库,更多讨论和示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.