
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Match at the End of String in Python Using Regular Expression
A regular expression in Python is a set of characters that allows you to use a search pattern to find a string or a group of strings. These are used within Python using the re package.
To match the end of the string in Python by using a regular expression, we use the following regular expression -
^/w+$
Here,
-
$ implies the start with.
-
/w returns a match where the string contains any word characters (a-z, A Z, 0-9, and underscore character).
-
+ indicates one or more occurrences of a character.
Using re.search() method
The re.search() function in Python searches the string for a match and returns a match object if there is any match. The group() method is used to return the part of the string that is matched.
Example
Here is an example for showing the usage of the re.search() method -
import re s = 'tutorialspoint is a great platform to enhance your skills' result = re.search(r'\w+$', s) print(result.group())
The following output is obtained on executing the above program -
skills
Using re.findall() method
The method findall(pattern, string) in Python locates every occurrence of the pattern within the string. The dollar sign ($) guarantees that you only match the word Python at the end of the string when you use the pattern "\w+$".
Example
Here is an example showing the usage of the re.findall() method -
import re text = 'tutorialspoint is a great platform to enhance your skills' result = re.findall(r'\w+$', text) print(result)
Following is an output of the above code -
['skills']
Using re.match() method
The re.match() method checks for a match only at the beginning of the string. However, we can use it with the pattern "\w+$" to match the word at the end of the string by providing the entire string as input.
Example
Here is an example demonstrating the usage of the re.match() method -
import re text = 'tutorialspoint is a great platform to enhance your skills' result = re.match(r'.*\b(\w+)$', text) if result: print(result.group(1))
The following output is obtained on executing the above program -
skills