0

I would like to remove the symbol "|" but only when it is at the beginning of a sentence (e.g., I want "|pediatrics" to become "pediatrics" but "pediatrics|clinical" should not be changed.

I tried

sub('[|[:alnum:]]','', "word")

which works well in the case where "|" is indeed at the beginning of the sentence, but removes the first letter when it is not present (i.e.,

sub('[|[:alnum:]]','', "|pediatrics")

returns pediatrics as desired but

sub('[|[:alnum:]]','', "pediatrics")

returns ediatrics...

Any help would be extremely valuable! Thanks in advance.

Progman
  • 16,827
  • 6
  • 33
  • 48
ClaraJ
  • 57
  • 4

1 Answers1

1

You can use ^ to specify start of the string and since | has a special meaning in regex, escape it with \\. With sub you may do -

x <- c('|pediatrics', 'pediatrics|clinical')
y <- sub('^\\|', '', x)
y
#[1] "pediatrics"          "pediatrics|clinical"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213