Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a whitespace before "((VERB)" only if it is not preceded by a space or the beginning of the string?

import re

#input string example:
input_text = "((VERB)ayudar a nosotros) ár((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)"


#this give me a raise error("look-behind requires fixed-width pattern") re.error: look-behind requires fixed-width pattern
#input_text = re.sub(r"(?<!^|\s)\(\(VERB\)", " ((VERB)", input_text)

#and this other option simply places a space in front of all ((VERB) ) 
# without caring if there is a space or the beginning of the string in front 
input_text = re.sub(r"(^|\s)\(\(VERB\)", lambda match: match.group(1) + "((VERB)", input_text)

print(repr(input_text)) # --> output

I have tried using (^|\s) as it is a capturing group that looks for the start of the string ^ or a whitespace just before the pattern "((VERB)". Another pattern option could be with a non-capturing group (?:|) or better still using a context limiter like look-behind (?<!^|\s)

This is the output you should be getting when running this script:

"((VERB)ayudar a nosotros) ár ((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can assert a non whitespace char to the left:

(?<=\S)\(\(VERB\)

Regex demo | Python demo

In the replacement use a space followed by the full match r" \g<0>"

import re

input_text = "((VERB)ayudar a nosotros) ár((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)"
input_text = re.sub(r"(?<=\S)\(\(VERB\)", r" \g<0>", input_text)
print(input_text)

Output

((VERB)ayudar a nosotros) ár ((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading