re.search匹配到多次
时间: 2024-02-03 07:25:23 浏览: 16
可以使用正则表达式中的括号和管道符号来匹配多个模式。
例如,如果要匹配字符串中的"apple"或"orange",可以使用以下正则表达式:
```
import re
string = "I like apples and oranges."
pattern = r"apple|orange"
result = re.search(pattern, string)
if result:
print("Match found:", result.group())
else:
print("No match found.")
```
输出:
```
Match found: apples
```
在正则表达式中,管道符号 "|" 表示 "或" 的意思。在上面的例子中,正则表达式 "apple|orange" 匹配字符串中的 "apple" 或 "orange"。
如果要匹配多个模式,可以使用括号将它们分组,并使用管道符号将它们连接起来。例如,如果要匹配字符串中的 "apple"、"orange" 或 "banana",可以使用以下正则表达式:
```
import re
string = "I like apples, oranges, and bananas."
pattern = r"(apple|orange|banana)"
result = re.search(pattern, string)
if result:
print("Match found:", result.group())
else:
print("No match found.")
```
输出:
```
Match found: apples
```
在上面的例子中,正则表达式 "(apple|orange|banana)" 匹配字符串中的 "apple"、"orange" 或 "banana"。括号将这三个模式分组,管道符号将它们连接起来。