2016-07-03 95 views
-5

如果字符串的第一行包含给定的“sub”字符串,我想匹配一个字符串。这是可能的蟒蛇使用oneliner正则表达式?python中的条件正则表达式

string="abcd - testing xxx 
foo bar 
end" 

如果字符串FIRSTLINE包含:

"abcd - testing" 

匹配整个字符串:

"abcd - testing xxx 
foo bar 
end" 

的问题是输出被另一个Python程序,这是我无法控制的读。

我只能用一个正则表达式ONELINE提供该程序...

谢谢。

+4

你可能不需要一个正则表达式:'my_string.startswith(“ABCD - 测试”)' –

+1

那你试试,你有什么问题与模式,你试过吗? –

+0

你的意思是“正则表达式”是由另一个程序读取的......而不是“输出”。 “输出”意味着你指的是匹配的字符串。 – Resonance

回答

0

使用此:

string = """abcd - testing xxx 
foo bar 
end""" 

sub = "abcd - testing" 

def match(string, sub): 
    return string if sub in string.splitlines()[0] else '' 

print match(string, sub) 
  • splitlines()将你的主要字符串分割成线
  • [0]会选择第一行
  • in将返回true,如果你的子字符串包含在第一行
+0

是否可以在一个oneline正则表达式中拆分字符串? – user3030473

+1

为什么你必须使用正则表达式? – Daniel

0

enter image description here

这将工作。

^.*abcd - testing.*\n(?:.*\n?)+$