正则表达式前瞻断言的使用案例

18 min read

正则表达式前瞻断言是一种非捕获的匹配模式,用于在匹配过程中确定一个位置的后面跟着某个模式。

以下是几个使用正则表达式前瞻断言的案例:

  1. 匹配包含数字的文本,但不包含小数点:
import re

pattern = r"\d+(?!\.)"
text = "123.45 678 90"
matches = re.findall(pattern, text)
print(matches)  # Output: ['678', '90']

在这个例子中,正则表达式r"\d+(?!\.)"使用了前瞻断言(?!\.)来匹配数字,并排除了那些后面跟着小数点的数字。

  1. 匹配包含英文单词的句子,但不包含特定单词:
import re

pattern = r"\b(?!(?:a|an|the)\b)\w+\b"
text = "The cat is on the table"
matches = re.findall(pattern, text, re.IGNORECASE)
print(matches)  # Output: ['cat', 'is', 'on', 'table']

在这个例子中,正则表达式r"\b(?!(?:a|an|the)\b)\w+\b"使用了前瞻断言(?!(?:a|an|the)\b)来匹配单词,并排除了那些被指定的特定单词所紧跟的单词。

  1. 匹配包含指定模式但不以特定模式结束的URL:
import re

pattern = r"https?://\w+(?=/|$)"
text = "http://www.example.com https://www.example.com/abc"
matches = re.findall(pattern, text)
print(matches)  # Output: ['http://www.example.com', 'https://www.example.com']

在这个例子中,正则表达式r"https?://\w+(?=/|$)"使用了前瞻断言(?=/|$)来匹配以指定模式https?://\w+开始但不以/或字符串结束作为结束的URL。

这些案例展示了正则表达式前瞻断言的使用,它可以帮助我们更精确地匹配符合特定条件的文本。