stringr str_extract capture group capturing everything

后端 未结 3 983
无人共我
无人共我 2021-02-20 09:09

I\'m looking to extract the year from a string. This always comes after an \'X\' and before \".\" then a string of other characters.

Using stringr\'s

3条回答
  •  不思量自难忘°
    2021-02-20 09:54

    I believe the most idiomatic way is to use str_match:

    str_match(string = 'X2015.XML.Outgoing.pounds..millions.',
              pattern = 'X(\\d{4})\\.')
    

    Which returns the complete match followed by capture groups:

         [,1]     [,2]  
    [1,] "X2015." "2015"
    

    As such the following will do the trick:

    str_match(string = 'X2015.XML.Outgoing.pounds..millions.',
              pattern = 'X(\\d{4})\\.')[2]
    

提交回复
热议问题