Python Regular Expressions (RegEx) Basic Matching
Page Info
Content
Python Regular Expressions (RegEx) Basic Matching
In Python, the re
module allows you to work with regular expressions to search, match, and manipulate strings. Regular expressions are patterns used to match character sequences in text.
Importing the re Module
import re
Basic Matching Using re.match()
import re
pattern = r"Hello"
text = "Hello, World!"
# Check if the pattern matches at the beginning
match = re.match(pattern, text)
if match:
print("Match found:", match.group())
else:
print("No match")
# Output: Match found: Hello
Explanation:
re.match(pattern, text)
: Checks for a match only at the beginning of the string.match.group()
: Returns the matched text.
Searching Anywhere in the String Using re.search()
pattern = r"World"
text = "Hello, World!"
search = re.search(pattern, text)
if search:
print("Found:", search.group())
# Output: Found: World
Explanation:
re.search()
: Searches for the pattern anywhere in the string, not just at the beginning.
Finding All Matches Using re.findall()
text = "Python 3.9, Python 3.10, Python 3.11"
pattern = r"Python \d+\.\d+"
matches = re.findall(pattern, text)
print(matches)
# Output: ['Python 3.9', 'Python 3.10', 'Python 3.11']
Explanation:
re.findall()
returns a list of all matches in the string.\d+
matches one or more digits,\.
matches a literal dot.
Key Points
- Use
re.match()
for matching at the start of a string. - Use
re.search()
to find a pattern anywhere in the string. - Use
re.findall()
to get all occurrences of a pattern. - Regular expressions allow complex string matching, extraction, and validation.
SEO Keywords
Python regex example, Python re module, Python match string, Python search pattern, Python findall, Python regular expressions basics
Python regular expressions are powerful tools for pattern matching, text extraction, and string validation, making data parsing and manipulation efficient.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.