2013-03-19 11 views
1

我需要兩個不同的正則表達式。第一個是匹配一年的最後兩位數字,例如如果我有「2010」我想獲得「10」。我試着做類似正則表達式獲取年份和姓氏的前三個字母的最後幾位

\d{2}\Z 

但它沒有工作。 第二個是兩個獲取由「和」分隔的各種名字和姓氏的前三個字母。 比如我有

John Smith and Paul Anthony Doe 

我想返回「SmiDoe」,但只有「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保羅AnthonySam2010」,我想獲得「SmiSam10」。

+2

「但它沒有工作」 - 謹慎地告訴我們如何? – georg 2013-03-19 19:58:52

+0

爲什麼2個不相關的問題一次?請一次提出一個問題。 – nhahtdh 2013-03-19 20:26:21

+0

@nhahtdh我應該發佈另一個問題,包括編輯?對不起,我對SO非常陌生 – petobens 2013-03-19 20:58:45

回答

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

哎呀,我覺得很累。 +1代表我的愚蠢:) – root 2013-03-19 20:49:30

+0

關於我的編輯,Ultisnips允許Python插值,因此我能夠使用您的解決方案並避免使用正則表達式。 – petobens 2013-03-21 18:04:44

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 ,顯然想要在比賽中的第一項

+1

鏈接到異地解決方案是一種糟糕的形式。它使這個網站更難搜索。而且我們不知道這個外國網站可以使用多久,或者它保留了多長時間的數據。 – 2013-03-19 20:44:46

+0

感謝您的評論,我最近的修改如何? – Brett 2013-03-19 22:19:47

相關問題