Multiline in Python Regular Expressions
Regular expressions have their own peculiarities when working with multi-line strings. Let's look at them using the following string as an example, containing regular characters, line feed characters, and tabs:
pythontxt = '''111
222
333
444'''
Line break
Newline characters can be caught with the '\n' command:
pythonres = re.sub('\n', '!', txt)
print(res)
The result will be the following line (the spaces between lines are tabs):
python'111! 222! 333! 444'
Tabulation
Tab characters can be caught with the '\t' command:
pythonres = re.sub('\t', '!', txt)
print(res)
Result of code execution:
python'''
!111
!222
!333
!444
'''
Work point
The '.' command for a multi-line string does not catch line feed characters:
pythonres = re.sub('.', '!', txt)
print(res)
Result of code execution:
python'''
!!!
!!!!
!!!!
!!!!
'''
Any symbol
To catch all characters in a multi-line string, a clever trick is used in the form of a combination of [\s\S]. This construction will find all regular characters and all line breaks:
pythonres = re.sub('[\s\S]', '!', txt)
print(res)
Result of code execution:
python'!!!!!!!!!!!!!!!!!!'
Dollar
The '$' command in multiline mode will catch the end of each line:
pythonres = re.sub('$', '!', txt)
print(res)
Result of code execution:
python'''
111!
222!
333!
444!
'''
Practical tasks
Given a string:
python'''
abc
def
ghi
jkl
'''
Write a regular expression that will transform this line into the following:
python'''
abc!
def!
ghi!
jkl!
'''
Given a string:
python'''
abc
def
ghi
jkl
'''
Write a regular expression that will transform this line into the following:
python'''
! abc
! def
! ghi
! jkl
'''
Given a string:
python'''
abc
def
ghi
jkl
'''
Write a regular expression that will transform this line into the following:
python'''!
abc
def
ghi
jkl
!'''
Given a string:
python'''
abc
def
ghi
jkl
'''
Write a regular expression that will transform this line into the following:
python'''!
! abc
! def
! ghi
! jkl
!'''
Given a string:
python'''
abc
def
ghi
jkl
'''
Write a regular expression that will transform this line into the following:
python'''!
abc!
def!
ghi!
jkl!
!'''
Given a string:
python'''
abc
def
ghi
jkl
'''
Write a regular expression that will transform this line into the following:
python'''
!abc
!def
!ghi
!jkl
'''