Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Regex将获取年份的最后一位数字和姓氏的前三个字母_Python_Regex - Fatal编程技术网

Python Regex将获取年份的最后一位数字和姓氏的前三个字母

Python Regex将获取年份的最后一位数字和姓氏的前三个字母,python,regex,Python,Regex,我需要两个不同的正则表达式。第一个是匹配一年的最后两位数,例如,如果我有“2010”,我想得到“10”。我试着做一些类似的事情 \d{2}\Z 但它不起作用。 第二个是两个,以“和”分隔不同姓名和姓氏的前三个字母。 比如我有 John Smith and Paul Anthony Doe 我希望正则表达式返回“SmiDoe”,但如果Doe不存在,则只返回“Smi”。这将是很好的,它也与更多的只是两个名字和姓氏 编辑:提供的解决方案工作得很好,现在我正试图使用它们使用Ultisnips插件为V

我需要两个不同的正则表达式。第一个是匹配一年的最后两位数,例如,如果我有“2010”,我想得到“10”。我试着做一些类似的事情

\d{2}\Z
但它不起作用。 第二个是两个,以“和”分隔不同姓名和姓氏的前三个字母。 比如我有

John Smith and Paul Anthony Doe
我希望正则表达式返回“SmiDoe”,但如果Doe不存在,则只返回“Smi”。这将是很好的,它也与更多的只是两个名字和姓氏

编辑:提供的解决方案工作得很好,现在我正试图使用它们使用Ultisnips插件为Vim构建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”

以下是获取最后两位数字的方法:

"/\d{2}$/" -> "2010" -> 10

要从字符串中获取姓氏的前三个字母:

"/\s(\w{,3})\w*($|\sand)/" -> "John Smith and Paul Anthony Doe" -> 1. Smi 2. Doe

,显然想要比赛中的第一个项目

你真的需要正则表达式吗,还是这样就可以了

>>> 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'

“但它不起作用”-想告诉我们确切的方法吗?为什么同时问两个不相关的问题?请一次问一个问题。@nhahdh我应该发布另一个问题,包括编辑吗?很抱歉,我还没有接触到非现场解决方案是一种糟糕的形式。这使得这个网站不易搜索。我们不知道这个外文站点可以使用多长时间,或者它保留数据的时间。关于我的编辑,Ultisnips允许Python插值,所以我可以使用你的解决方案,避免使用正则表达式。