以下是一个使用正则表达式在两个模式之间打印字符串的脚本的示例代码:
import re
def print_last_match(string, pattern1, pattern2):
# 使用正则表达式找到第一个匹配的结果
match1 = re.search(pattern1, string)
if match1:
# 使用正则表达式找到最后一个匹配的结果
match2 = re.findall(pattern2, string)
if match2:
last_match = match2[-1]
print(last_match)
# 测试代码
string = "This is a test string. Hello world. This is another test."
pattern1 = r"test"
pattern2 = r"\b\w+\b"
print_last_match(string, pattern1, pattern2)
在上面的示例中,我们定义了一个名为print_last_match
的函数,该函数接受一个字符串、两个正则表达式模式作为参数。它首先使用re.search
函数找到第一个匹配的结果,然后使用re.findall
函数找到所有匹配的结果。最后,它将最后一个匹配的结果打印出来。
在测试代码中,我们定义了一个字符串和两个正则表达式模式,然后调用print_last_match
函数来打印最后一个匹配的结果。在这个例子中,第一个模式是"test",第二个模式是\b\w+\b
,它匹配字符串中的单词。
当运行这段代码时,它将打印出字符串中最后一个匹配的单词,即"test"。