Bhanu Prakash Reddy
Bhanu Prakash Reddy

Reputation: 1

Deleting a string between repeated delimiters in python

I have to remove the strings that start with "===" and also end with "===" (for example I have to replace the string "===Links===" with null string) in python. But the problem here is it can start with three "=" or four or any number of '='. I have tried to use the regex re.sub('[=]*.*?[=]*', '', string). But when it is run on "===Refs===", it is giving "Refs" as output instead of null string. Can you please suggest something for this?

Upvotes: 0

Views: 66

Answers (3)

Xenobiologist
Xenobiologist

Reputation: 2151

Too late :-(

import re
str = '===Links=== are great, but ===Refs=== bla bla == blub ===blub'

pattern = re.compile('=+\w+=+')
replaced = re.sub(pattern, '', str)
print(replaced)

Upvotes: 1

RnD
RnD

Reputation: 1069

import re

string = '===Ref==='
pattern = r'^\=+.+\=+$'

string = re.sub(pattern, '', string)

Upvotes: 2

Moberg
Moberg

Reputation: 5493

.? suggests that you are only accepting no or a single character between your =s. Try changing it to .* to match multiple characters between =s.

Perhaps you can use str.startswith() and str.endswith() to find out if the string starts/ends with ===?

Upvotes: 0

Related Questions