Reputation: 101
I have been given a sentence in which two words are separated by a comma:
i.e.
The big, fast bug ate the slower one.
and asked the write a regular expression to reverse the order of the two words about the comma so it prints:
'The fast, big bug...'
What I have so far:
I am thinking it involves a findall
for the comma and space and then a reverse function of some sort.
Upvotes: 3
Views: 7931
Reputation: 67968
(\w+)(\s*),(\s*)(\w+)
Try this.Replace by \4\2,\3\1
.See demo.
http://regex101.com/r/tF5fT5/32
import re
p = re.compile(ur'(\w+)(\s*),(\s*)(\w+)', re.IGNORECASE)
test_str = u"The big, fast bug ate the slower one."
subst = ur"\4\2,\3\1"
result = re.sub(p, subst, test_str)
Upvotes: 3
Reputation: 8709
You need re.sub()
for this as:
>>> a="The big, fast bug ate the slower one. The quick, brown fox jumps over the lazy dog"
>>> re.sub(r'\s(\w*),\s+(\w*)\s',r' \2, \1 ',a)
'The fast, big bug ate the slower one. The brown, quick fox jumps over the lazy dog'
It only substitutes words separated by ',' with same words in reverse order, leaving rest of the string as it is.
Upvotes: 3
Reputation: 52393
import re
re.sub('(\w+)\s*,\s*(\w+)', '\\2, \\1', )
re.sub('(\w+)\s*,\s*(\w+)', '\\2, \\1', 'The fast, big bug')
'The big, fast bug'
\s* matches zero or more space
\w+ matches a word. \w is basically [a-zA-Z0-9_]
Backward reference \1 (escaped as \\1) replaces first substring match and so on
We are trying to match only the words on either side of comma and switch the matched substrings
https://docs.python.org/2/library/re.html
Upvotes: 1