In python 3, for string replacement, how do I do all combinations of: case sensitive/case insensitive, word base/non-word based, and full replacement/including the original text?
Asked
Active
Viewed 42 times
-1
-
Possible duplicate of [Do Python regular expressions from the re module support word boundaries (\b)?](https://stackoverflow.com/questions/3995034/do-python-regular-expressions-from-the-re-module-support-word-boundaries-b) – Tim Biegeleisen Oct 26 '19 at 05:18
1 Answers
0
This can be done using regex from within Python. Examples for Python 3:
import re
test_string = 'Will william unwillingly goodwill (WiLl)?'
#case sensitive find and replace
to_match = re.compile('will')
new_string = re.sub(to_match, 'what', test_string)
print('Example 1: ' + new_string)
#case insensitive find and replace
to_match = re.compile('will', re.IGNORECASE)
new_string = re.sub(to_match, 'what', test_string)
print('Example 2: ' + new_string)
#word based case insensitive find and replace
to_match = re.compile(r'\bwill\b', re.IGNORECASE)
new_string = re.sub(to_match, 'what', test_string)
print('Example 3: ' + new_string)
#word based case insensitive find and replace including original text
to_match = re.compile(r'(\bwill\b)', re.IGNORECASE)
new_string = re.sub(to_match, r'{\1}', test_string)
print('Example 4: ' + new_string)
#start of word based find and replace
to_match = re.compile(r'\bwill', re.IGNORECASE)
new_string = re.sub(to_match, 'what', test_string)
print('Example 5: ' + new_string)
#Case insensitive find and replace with original text, but in uppercase
def upper_replace(match):
return '{' + match.group(1).upper()
to_match = re.compile(r'(will)\b', re.IGNORECASE)
new_string = re.sub(to_match, upper_replace, test_string)
print('Example 6: ' + new_string)
This outputs:
Example 1: Will whatiam unwhatingly goodwhat (WiLl)?
Example 2: what whatiam unwhatingly goodwhat (what)?
Example 3: what william unwillingly goodwill (what)?
Example 4: {Will} william unwillingly goodwill ({WiLl})?
Example 5: what whatiam unwillingly goodwill (what)?
Example 6: {WILL william unwillingly good{WILL ({WILL)?
Let me know if more basic string replace use cases need to be covered.

Christopher Pratt
- 167
- 7