Skip to content Skip to sidebar Skip to footer

How To Ignore Unmatched Group In A String In Re Python?

I have a string input of s = 'horse dog cat bear' for which I want to change the order of the words as cat horse dog bear The corresponding re would be >>> import re &g

Solution 1:

Try

r'(horse )((?:dog )?)(cat )(bear)'

I.e. make the contents of the capturing group optional, not the group itself.


Solution 2:

Do you need to use re ? You can do ti with lists.

s0 = 'horse dog cat bear'
s1 = 'horse cat bear'
s_map = 'cat horse dog bear'.split()

print(" ".join([x for x in s_map if x in s0.split()]))
print(" ".join([x for x in s_map if x in s1.split()]))

Output:

cat horse dog bear
cat horse bear

Post a Comment for "How To Ignore Unmatched Group In A String In Re Python?"