深度阅读

How to use the "?" character in regular expressions to make a pattern optional?

作者
作者
2023年08月22日
更新时间
11.06 分钟
阅读时间
0
阅读量

Here’s how to use the “?” character in regular expressions to make a pattern optional:

In regular expressions, the “?” character is used as a quantifier to make the preceding token optional. This means that the pattern that precedes the “?” character can match either zero or one occurrences of the token. For example:

import re

pattern = r'colou?r'  # regex pattern to match "color" or "colour"
text1 = 'The sky is blue'
text2 = 'The favourite colour is red'

match1 = re.search(pattern, text1)
match2 = re.search(pattern, text2)

if match1:
  print(match1.group())  # Output: None (no match found)
if match2:
  print(match2.group())  # Output: 'colour'

This will match both “color” and “colour” in a flexible way, making the letter “u” optional. In this example, the re.search() function returns the first non-overlapping occurrence of the regex pattern in the given string. If the pattern is not found in the string, re.search() will return None.

You can modify the pattern to make different parts of the pattern optional or to match different types of substrings in the string.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。