[英]Check two conditions in line
I have the following lines and I want to match the first one based one the condition that it starts with a '%' and contains a '=' sign:我有以下几行,我想匹配第一个基于它以“%”开头并包含“=”符号的条件:
% This comment is = True
% This comment is equal true
I want to use python's re
module to be able to extract the first sentence on the basis that it starts with a %
and contains a =
.我想使用 python 的
re
模块能够提取第一句话,因为它以%
开头并包含一个=
。
So far, I have gathered that I need something like:到目前为止,我已经收集到我需要类似的东西:
...
if re.match('^%' ,line):
...
but cannot figure out the rest.但无法弄清楚其余的。 Thank you!
谢谢!
You really don't need regex for this:你真的不需要正则表达式:
if line[0] == '%' and '=' in line:
OR要么
if line.startswith('%') and '=' in line:
That being said, you can use regex like this:话虽如此,您可以像这样使用正则表达式:
if re.match('%.*='):
Or better yet:或者更好:
pattern = re.compile('%.*=')
...
if pattern.match(line):
re.match
already implies that your regex begins with ^
. re.match
已经暗示您的正则表达式以^
开头。
If you don't want to allow %=
, you still don't really need regex, but it's a bit simpler to use it.如果您不想允许
%=
,您仍然不需要正则表达式,但使用它会更简单一些。 Without regex you can do something like没有正则表达式,你可以做类似的事情
if line[0] == '%' and line[1] != '=' and '=' in line[2:]:
Using regex, you can do使用正则表达式,你可以做到
if re.match('%[^=]+=', line):
I would argue that the second is more elegant.我认为第二种更优雅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.