Alistair W
Alistair W

Reputation: 390

Regex to match strings that are all punctuation but not strings with punctuation containing other characters

I have some messy text responses that I'm trying to cleanup a little. I'm using R and want to match responses that are all punctuation for removal.

Is there a regexp I can use to match these:

!@#$
.
**********

But not these:

Hello.
!asdf
**********1

I had previously tried

x[grepl("^[[:punct:]+]", x)]

which only matches punctuation at first character with another punctuation character

Upvotes: 1

Views: 3807

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

Simply use negation..

x[!grepl("\\w", x)] 

or

x[!grepl("[a-zA-Z]", x)] 

Your regex x[grepl("^[[:punct:]+]", x)] should check for a punctuation exists at the start.

Upvotes: 3

vks
vks

Reputation: 67968

^[^\\w\\n]+$

You can use this.See demo.

https://regex101.com/r/cZ0sD2/6

Upvotes: 1

Related Questions