We start our introduction to regular expressions in Python by using a basic search method to match strings provided by the re
module.
.search(regex, string)
takes a regular expression and a string as an input, and scans through the entire input string, and looks for a location where the given regex pattern finds a match.
Since this is an introduction to regular expressions, we will only use this method from
re
module. There are other methods from the module which provide more functionality. However, hold that thought for now.
Let's look at a simple example of this search method.
Since the string contained '123', the pattern '123' is instantly matched with the string s
in this example.
xxxxxxxxxx
12
// Adding a function to wrap the existing code
function findMatch() {
let s = 'hello123';
if (s.search('123') != -1) {
console.log("Found a match!");
} else {
console.log("Did not find a match.");
}
}
// Driver code to execute the function
findMatch();
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment