我正在尝试缩短字符串中的一些正则表达式匹配。这是一个例子
vYears = c('Democrat 2000-2004',
'Democrat 2004-2008',
'Democrat 2008-2012',
'Republican 2000-2004',
'Republican 2004-2008',
'Republican 2008-2012',
'Tossup')
我可以匹配我想要的表达式,并获得匹配,如此
grepYears = gregexpr('20[0-9]{2}', vYears)
regmatches(vYears, grepYears)
但是,我正在尝试将字符串缩短为
vYearsShort = c('Democrat 00-04',
'Democrat 04-08',
'Democrat 08-12',
'Republican 00-04',
'Republican 04-08',
'Republican 08-12',
'Tossup')
我怎样才能做到这一点?
答案 0 :(得分:3)
您可以使用gsub
。利用反向引用来捕获所需的部分:
> vYears = c('Democrat 2000-2004',
+ 'Democrat 2004-2008',
+ 'Democrat 2008-2012',
+ 'Republican 2000-2004',
+ 'Republican 2004-2008',
+ 'Republican 2008-2012',
+ 'Tossup')
> vYearsShort = gsub("20([0-9]{2})", "\\1", vYears)
> vYearsShort
[1] "Democrat 00-04" "Democrat 04-08" "Democrat 08-12" "Republican 00-04"
[5] "Republican 04-08" "Republican 08-12" "Tossup"
答案 1 :(得分:1)