alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[941] re module in Python

The re module in Python is used for regular expressions. It provides a set of functions that allows us to search a string for a match, replace substrings, and more, using regular expressions. Here's a basic guide on how to use the re module:

1. Import the re module:

import re

2. Basic Patterns and Functions:

a. re.search(pattern, string):

Search for a pattern in a string. Returns a match object if found, None otherwise.

- My view: it only returns the first match object.

pattern = r"apple"
string = "I love apples"
match = re.search(pattern, string)
if match:
print("Pattern found:", match.group())
else:
print("Pattern not found")

b. re.match(pattern, string):

Check if the pattern matches at the beginning of the string.

- My view: it only matches from the beginning and the only one.

pattern = r"Hello"
string = "Hello, world!"
match = re.match(pattern, string)
if match:
print("Pattern found at the beginning:", match.group())
else:
print("Pattern not found at the beginning")

c. re.findall(pattern, string):

Find all occurrences of a pattern in a string.

- My view: it will return all the match objects.

pattern = r"\d+" # Match one or more digits
string = "There are 123 apples and 456 oranges."
matches = re.findall(pattern, string)
print("Matches:", matches)

3. Regular Expression Patterns:

  • \d: Matches any digit (0-9).
  • \w: Matches any alphanumeric character (equivalent to [a-zA-Z0-9_]).
  • .: Matches any character except a newline.
  • *: Matches 0 or more occurrences of the preceding character.
  • +: Matches 1 or more occurrences of the preceding character.
  • ?: Matches 0 or 1 occurrence of the preceding character.
  • ^: Anchors the match at the beginning of the string.
  • $: Anchors the match at the end of the string.

4. Groups and Capturing:

pattern = r"(\d+)-(\w+)"
string = "123-apple"
match = re.search(pattern, string)
if match:
print("Full match:", match.group(0))
print("Number:", match.group(1))
print("Fruit:", match.group(2))

These are just some basics to get you started. Regular expressions can get quite complex, and you can create more sophisticated patterns for different matching scenarios. The re module provides various functions and flags for customization, so refer to the official documentation for more details.

posted on   McDelfino  阅读(11)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2015-11-17 【178】人生时间表
2013-11-17 【132】iPad使用相关问题
2011-11-17 【003】◀▶ C#学习(二) - 函数与相关类
2011-11-17 【C016】指数的十六进制很规则
点击右上角即可分享
微信分享提示