Word Boundaries in Python Regular Expressions
The '\\b' command references a word boundary, while '\B' or '\\B' do not reference a boundary. Note that Python strictly uses double-slash escaping for word boundaries, while other commands allow a single slash. Let's see how these commands work with examples.
Example
Let's wrap each word in the symbol '!':
pythontxt = 'aaa aaa aaa'
print(re.sub('\\b', '!', txt))
Result of code execution:
python'!aaa! !aaa! !aaa!'
Example
Let's add the symbol '!' in the spaces between the letters:
pythontxt = 'aaa aaa aaa'
print(re.sub('\\B', '!', txt))
Result of code execution:
python'a!a!a a!a!a a!a!a'
Practical tasks
Задание 1
Given a string:
pythontxt = 'abc def xyz'
Write a regular expression that will transform this line into the following:
python'#abc# #def# #xyz#'
Задание 2
Given a string:
pythontxt = 'abc def xyz'
Write a regular expression that will transform this line into the following:
python'a+b+c d+e+f x+y+z'