Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract all text before first numeric character only in R

Tags:

regex

r

gsub

I have a variable x that is a series of characters such as:

"W1W", "BT3", "BS5", "E1W", "B68"

From this I need to extract the characters before the first numeric character to get e.g.

"W", "BT", "BS", "E", "B"

I have tried looking through previous questions and found:

gsub("[^a-zA-Z]", "", x)

but this keeps the text characters following the numeric character and results in:

"WW", "BT", "BS", "EW", "B"

Is there any way to get only the leading text characters before the numeric character and drop everything afterwards?

like image 488
Mel Avatar asked Oct 16 '25 06:10

Mel


2 Answers

You may use

sub("^(\\D+).*", "\\1", x)

If there must be a digit and the digits can be at the start (and you need empty values then), use

sub("^(\\D*)\\d.*", "\\1", x)

See the regex demo and regex demo #2

The regex matches

  • ^ - start of string
  • (\D*) - 0+ non-digit symbol
  • \d - a digit
  • .* - any 0+ chars to the end of the string
like image 66
Wiktor Stribiżew Avatar answered Oct 18 '25 19:10

Wiktor Stribiżew


Using x in the Note at the end, remove everything from the first digit onwards:

sub("\\d.*", "", x)
## [1] "W"  "BT" "BS" "E"  "B" 

Note

x <- c("W1W", "BT3", "BS5", "E1W", "B68")
like image 40
G. Grothendieck Avatar answered Oct 18 '25 20:10

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!