我有一个字符串列表。 如果这些字符串中的任何一个具有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]
这些都不起作用。
你能告诉我我做错了吗?
答案 0 :(得分:2)
这样的事情似乎适用于琐碎的数据:
>>> 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']
答案 1 :(得分:1)
看起来您在结果字符串上的唯一界限位于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]
答案 2 :(得分:0)
我不完全确定您的用例,但以下代码可以为您提供一些提示:
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']
答案 3 :(得分:0)
你实际上与列表理解非常接近,但你的语法是关闭的 - 你需要将第一个表达式设为&#34;条件表达式&#34;又名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]