R - gsub specific character of a certain position

I would like to remove the last character of the variable. I was wondering if it is possible to select a position with gsuband delete a character in that particular position.

In this example, I want to delete the last digit at the end after Efor my 4 variables.

variables = c('B10243E1', 'B10243E2', 'B10243E3', 'B10243E4')
gsub(pattern = '[[:xdigit:]]{8}.', replacement = '', x = variables)

I thought we could use the command

{}

to select a specific position.

+4
source share
4 answers

You can do this by capturing all characters except the last:

variables = c('B10243E1', 'B10243E2', 'B10243E3', 'B10243E4')
gsub('^(.*).$', '\\1', variables)

Explanation:

  • ^ - beginning of line
  • (.*) - All characters, but a new line before
  • .$- last character (taken off .) to the end of the line ( $).

, , , .

:

[1] "B10243E" "B10243E" "B10243E" "B10243E"  

( , T ):

variables = c('B10247E1T', 'B10243E2T', 'B10243E3T', 'B10243E4T')
gsub('^(.{7}).', '\\1', variables)

( ET , ):

[1] "B10247ET" "B10243ET" "B10243ET" "B10243ET" 
+2

. , E , E, 7 , , 8 , 7 . , variables , .

sub(".$", "", variables)

sub("E.*", "E", variables)

sub("^(.{7}).", "\\1", variables)

sub("^(.{7}).*", "\\1", variables)

substr(variables, 1, 7)

substring(variables, 1, 7)

trimws("abc333", "right", "\\d") # requires R 3.6 (currently r-devel)

:

^(.{7}).

Regular expression visualization

Debuggex Demo

:

^(.{7}).*

Regular expression visualization

Debuggex Demo

+4

E, E

sub("E(.*)", 'E', variables)
## [1] "B10243E" "B10243E" "B10243E" "B10243E"

7 ,

sub("(?<=.{7})(.)", "", variables, perl = TRUE)
## [1] "B10243E" "B10243E" "B10243E" "B10243E"
+1
source
library(stringr)
str_sub("your String", 1, -2)

may be slower than others, but much easier to read.

0
source

All Articles