To find phone numbers in a string using regex in Python, you can use a regular expression and the re
module.
Here's an example code block that matches ten-digit phone numbers (in the format XXX-XXX-XXXX) in a string s
:
main.py163 chars9 lines
In this example, phone_regex
is a compiled regular expression pattern that matches the format of a phone number. The pattern r'\d{3}-\d{3}-\d{4}'
specifies that it should match a string of exactly ten digits, separated by two hyphens.
We then use the search
method to look for the first occurrence of this pattern in the string s
. If we find a match, we print it using the group
method of the match object.
You can adjust the regular expression pattern to match other formats of phone numbers as needed.
gistlibby LogSnag