如何编写正则表达式来提取字符串中最后一个逗号后面的单词? 例如在“Nelson,Nelson,New Zealand”中,我如何从字符串中提取新西兰?
答案 0 :(得分:3)
您不需要正则表达式。
s = "Nelson,Nelson, New Zealand"
print s.split(",")[-1]
New Zealand
只需在","
上拆分并获取最后一个元素。
使用s.split(",")[-1].strip()
删除空格。
答案 1 :(得分:2)
尝试使用以下正则表达式,它在逗号后抓取最后一个单词并将其存储到一个组中。同样,存储的组通过group()方法打印回来。
>>> import re
>>> str = 'Nelson,Nelson, New Zealand'
>>> match = re.search(r'.*, (.*)$', str)
>>> match.group(1)
'New Zealand'
答案 2 :(得分:1)
使用str.rpartition
代替正则表达式来完成这些简单的任务:
>>> s = "Nelson,Nelson, New Zealand"
>>> s.rpartition(',')[2].strip()
'New Zealand'
对于正则表达式,您可以使用例如
>>> m = re.search(r'([^,]*)$', s)
>>> m.group(1)
' New Zealand'
删除逗号后面的空格
>>> m = re.search(r'\s*([^,]*)$', s)
>>> m.group(1)
'New Zealand'