Regular expressions in Python
Regular expressions are used to search for and manipulate patterns in text. Here's an example of using regular expressions to match a phone number:
python
import re
pattern = r"\d{3}-\d{3}-\d{4}"
text = "Call me at 123-456-7890"
match = re.search(pattern, text)
if match:
print("Phone number found:", match.group())
else:
print("Phone number not found.")
In this example, we import the re module to use regular expressions. We define a pattern that matches a phone number in the format "###-###-####". We then search for the pattern in the string "Call me at 123-456-7890" using the search function. If a match is found, we print the phone number. Otherwise, we print a message indicating that no phone number was found.
No comments:
Post a Comment