我需要两个不同的正则表达式。第一个是匹配年份的最后两位数字,例如,如果我有“2010”,我想获得“10”。我尝试做类似的事情
\d{2}\Z
但是没有成功。 第二个是两个获取各个名字和姓氏的前三个字母,并用“and”分隔。 例如我有
John Smith and Paul Anthony Doe
我想要一个返回“SmiDoe”的正则表达式,但如果 Doe 不存在,则仅返回“Smi”。如果它不仅仅适用于两个名字和姓氏,那就太好了。
编辑:提供的解决方案工作完美,现在我尝试使用它们使用 Vim 的 Ultisnips 插件构建 bibtex(.bib 扩展名)片段。我尝试过的片段是
snippet ta "Test" b
@Article{${1/\s(\w{,3})\w*($|\sand)/$1/g}${2/\d{2}$/$0/g},
author={${1:John Smith and Paul Anthony Samuelson}}
year={${2:2010}}}
endsnippet
问题是,当扩展片段时,我得到“JohnSmi Paul AnthonySam2010”,我想获得“SmiSam10”。
最佳答案
你真的需要正则表达式吗?或者这个可以吗?
>>> def AbbreviateAuthors(names):
... return ''.join(i.split()[-1][:3] for i in names.split(' and '))
>>> AbbreviateAuthors('John Smith and Paul Anthony Doe and Chris Burns')
34: 'SmiDoeBur'
>>> AbbreviateAuthors('John Smith and Paul Anthony Doe')
35: 'SmiDoe'
>>> AbbreviateAuthors('John Smith')
36: 'Smi'
>>> AbbreviateAuthors('Smith')
37: 'Smi'
>>> AbbreviateAuthors('Sm')
38: 'Sm'
关于python - 正则表达式获取年份的最后一位数字和姓氏的前三个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15509167/