Beginning and End of String in Python Regular Expressions
There are special symbols that
denote the beginning '^' or the end
of a string '$'. Let's see how they work with examples.
Example
In this example, the search pattern is: replace 'aaa' with '!' only if it is at the beginning of the string:
txt = 'aaa aaa aaa'
res = re.sub('^aaa', '!', txt)
print(res)
Result of code execution:
'! aaa aaa'
Example
In this example, the search pattern is: replace 'aaa' with '!' only if it is at the end of the string:
txt = 'aaa aaa aaa'
res = re.sub('aaa$', '!', txt)
print(res)
Result of code execution:
'aaa aaa !'
Example
When the regular expression starts with '^',
and ends with '$', then the entire string
is checked for compliance with the regular expression.
In the following example, the search pattern is: letter 'a' repeated one or more times, replace the entire string with '!' only it consists of the letters 'a':
txt = 'aaa'
res = re.sub('a+$', '!', txt)
print(res)
Result of code execution:
'!'
Practical tasks
Given a string:
txt = 'abc def xyz'
Write a regular expression that will find the first substring of letters.
Given a string:
txt = 'abc def xyz'
Write a regular expression that will find the last substring of letters.