[英]list comprehension using regex conditional
我有一个字符串列表。 如果这些字符串中的任何一个具有4位数年份,我想在年末截断该字符串。 否则我就把绳子单独留下。
我试过用:
for x in my_strings:
m=re.search("\D\d\d\d\d\D",x)
if m: x=x[:m.end()]
我也尝试过:
my_strings=[x[:re.search("\D\d\d\d\d\D",x).end()] if re.search("\D\d\d\d\d\D",x) for x in my_strings]
这些都不起作用。
你能告诉我我做错了什么吗?
像这样的东西似乎适用于琐碎的数据:
>>> regex = re.compile(r'^(.*(?<=\D)\d{4}(?=\D))(.*)')
>>> strings = ['foo', 'bar', 'baz', 'foo 1999', 'foo 1999 never see this', 'bar 2010 n 2015', 'bar 20156 see this']
>>> [regex.sub(r'\1', s) for s in strings]
['foo', 'bar', 'baz', 'foo 1999', 'foo 1999', 'bar 2010', 'bar 20156 see this']
看起来你对结果字符串的唯一限制是在end()
,所以你应该使用re.match()
代替,并将你的正则表达式修改为:
my_expr = r".*?\D\d{4}\D"
然后,在您的代码中,执行:
regex = re.compile(my_expr)
my_new_strings = []
for string in my_strings:
match = regex.match(string)
if match:
my_new_strings.append(match.group())
else:
my_new_strings.append(string)
或者作为列表理解 :
regex = re.compile(my_expr)
matches = ((regex.match(string), string) for string in my_strings)
my_new_strings = [match.group() if match else string for match, string in matches]
或者,您可以使用re.sub
:
regex = re.compile(r'(\D\d{4})\D')
new_strings = [regex.sub(r'\1', string) for string in my_strings]
我不完全确定你的用例,但下面的代码可以给你一些提示:
import re
my_strings = ['abcd', 'ab12cd34', 'ab1234', 'ab1234cd', '1234cd', '123cd1234cd']
for index, string in enumerate(my_strings):
match = re.search('\d{4}', string)
if match:
my_strings[index] = string[0:match.end()]
print my_strings
# ['abcd', 'ab12cd34', 'ab1234', 'ab1234', '1234', '123cd1234']
你实际上与列表理解非常接近,但你的语法是关闭的 - 你需要使第一个表达式成为“条件表达式”, x if <boolean> else y
:
[x[:re.search("\D\d\d\d\d\D",x).end()] if re.search("\D\d\d\d\d\D",x) else x for x in my_strings]
显然这非常难看/难以阅读。 有几种更好的方法可以将字符串分成4位数年份。 如:
[re.split(r'(?<=\D\d{4})\D', x)[0] for x in my_strings]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.