Edward Fu
Edward Fu

Reputation: 137

Regular expression find matching string then delete everything between spaces

Pretty new to regex here so I'm not sure how to do this. FYI I'm using Python but I'm not sure how much that matters.

What I want to do is something like this:

string1 = 'Metro boomin on production wow'
string2 = 'A loud boom idk why I chose this as an example'
pattern = 'boom'
result = re.sub(pattern, ' ____ ', string1)
result2 = re.sub(pattern, ' ____ ', string2)

right now that would give me "Metro ____in on production wow" and "a loud ____ idk why I chose this as an example

What I want is both "Metro ______ on production wow" and "a loud ____ idk why I chose this as an example"

Basically I want to find a target string in another string, then replace that matching string and everything between 2 spaces into a new string

Is there a way I can do this? Also if possible, preferably with variable length in my replacement string based on the length of the original string

Upvotes: 0

Views: 155

Answers (1)

cs95
cs95

Reputation: 402533

You're on the right track. Just extend your regex a bit.

In [105]: string = 'Metro boomin on production wow'

In [106]: re.sub('boom[\S]*', ' ____ ', string)
Out[106]: 'Metro  ____  on production wow'

And,

In [137]: string2 = 'A loud boom'

In [140]: re.sub('boom[\S]*', ' ____', string2)
Out[140]: 'A loud  ____'

The \S* symbol matches zero or more of everything that is not a space.

To replace text with the same number of underscores, specify a lambda callback instead of a replacement string:

re.sub('boom[\S]*', lambda m: '_' * len(m.group(0)), string2)

Upvotes: 2

Related Questions