1

I need two different regex. The first one is to match the last two digits of a year, for instance if I have "2010" I would like to obtain "10". I tried doing something like

\d{2}\Z

but it didn't work. The second one is two obtain the first three letters of various names and surnames separated by "and". For instance I have

John Smith and Paul Anthony Doe

I would like a regex that returns "SmiDoe" but only "Smi" if Doe is not present. It would be nice it works also with more that just two names and surnames.

Edit: The provided solutions work perfectly, and now I'm trying to use them to build bibtex (.bib extension) snippets using Ultisnips plugin for Vim. The snippet I tried is

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

The problem is that when the snippet is expanded I get "JohnSmi Paul AnthonySam2010" and I would like to obtain "SmiSam10".

4

2 回答 2

2

你真的需要一个正则表达式,还是会这样做?

>>> 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'
于 2013-03-19T20:29:52.260 回答
1

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

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

http://rubular.com/r/IgVeKXucJ0

并从您拥有的字符串中获取姓氏的前三个字母:

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

http://rubular.com/r/f8OXDB9pDq,显然想要比赛中的第一项

于 2013-03-19T19:55:06.503 回答