Casper
Casper

Reputation: 1539

Regular expression to remove special characters from start or end of a string

I want to remove special characters from start or end of string,

@Can't&

Using regular expression and I've tired,

`[^\w\s]`

But this regular expression removes ' which is inside the word and return below word,

Cant 

Can't seem to wrap my head around this any ideas would be highly appreciated.

Upvotes: 1

Views: 544

Answers (2)

Charif DZ
Charif DZ

Reputation: 14751

Can be simplified like this:

  res = re.sub(r'^\W+|\W+$', '', txt)

Upvotes: 3

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

Use the following approach (using regex alternation ..|..):

import re

s = "@Can't&"
res = re.sub(r'^[^\w\s]+|[^\w\s]+$', '', s)
print(res)    # Can't

Upvotes: 2

Related Questions