Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having issues with REGEX in R using logical AND

Tags:

regex

r

For some reason, I can't get the logical AND operator to work in R REGEX.

Sample vector:

regv <- c('33x119','[33x119z','!-?2312zzy?')

I am trying to replace all punctuation at the first character position with a blank except for a left bracket "[" and an exclamation point "!".

r3 <- gsub('^[[[:punct:]]&&[^[\\]!]]{1}','', regv)

The result is the same the original vector. Any ideas? Should I use negative lookaheads?

like image 452
DougC Avatar asked Oct 16 '25 16:10

DougC


1 Answers

I'd probably do it via negation--replace any starting character that's not letter, number, whitespace, [, or !:

sub("^[^a-zA-Z0-9\\s\\[!]", '', regv)
# [1] "33x119"      "[33x119z"    "!-?2312zzy?"
like image 162
Gregor Thomas Avatar answered Oct 18 '25 08:10

Gregor Thomas



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!