Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep string after first number

Tags:

regex

r

This seems like it should be easy but I can't figure out which permutation of regex matching will result in extracting the whole string after the first number if the string. I can extract the string before the first number like so:

gsub( "\\d.*$", "", "DitchMe5KeepMe" )

Any idea how to write the regex pattern such that the string after the first number is kept?

like image 222
boshek Avatar asked Jun 06 '16 20:06

boshek


2 Answers

Instead of lazy dot matching, I'd rely on a \D non-digit character class and use sub to make just one replacement:

sub( "^\\D*\\d", "", "DitchMe5KeepMe" )

Here,

  • ^ - matches the start of a string
  • \D* - matches zero or more non-digits
  • \d - matched a digit

NOTE: to remove up to the first number, add a + after the last \d to match one or more digits.

See the IDEONE demo.

like image 87
Wiktor Stribiżew Avatar answered Oct 22 '22 22:10

Wiktor Stribiżew


What I can see is that you want to remove everything until the first number, so you can use this regex and replace it with an empty string:

^.*?\d

I used .*? to make the pattern ungreedy, so if you had DitchMe5Keep8Me it will match DitchMe5, if you use a greedy pattern like .*\d it would match DitchMe5Keep8

Regex 101 Demo

R Fiddle Demo

enter image description here

like image 41
Federico Piazza Avatar answered Oct 22 '22 21:10

Federico Piazza