silkfire
silkfire

Reputation: 25945

Matching (and removing) words that only consist of special characters

I'd like to match "words", i.e., strings surrounded by whitespace or strings located at the beginning or end of a text, but that only consist of special characters.

I came up with the following pattern but unfortunately it doesn't match what I'm expecting it to:

((?<!\w)\W(?!\w))+

For the following input:

word1 !!!$$£@€${/// word3 word€€}}}==4 word5 @£]][{

I'd like the following string returned after having all matches removed (word #2 and #6):

word1 word3 word€€}}}==4 word5

Upvotes: 1

Views: 273

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

What you ask for is basically

(?<!\S)\W+(?!\S)

where

  • (?<!\S) - matches start of string or a location right after a whitespace char
  • \W+ - 0+ non-word chars
  • (?!\S) - matches end of string or a location right before a whitespace char.

See the regex demo.

Upvotes: 1

Related Questions