gpt4 book ai didi

python - 正则表达式用于匹配不具有相同单词出现在另一个关键字之前的关键字

转载 作者:行者123 更新时间:2023-11-30 23:32:53 25 4
gpt4 key购买 nike

我需要找到“test”一词何时出现,后跟“follow”,中间没有另一个“test”。

示例:

test
word
word
word
test
test
word
word
follow
word
word
test

我只想要这个:

test
word
word
word
test
**test**
**word**
**word**
**follow**
word
word
test

不过,我对正则表达式不够熟悉,无法做到这一点。任何建议都会很棒。

编辑虽然单词 test 会在其中多次出现,但单词 follow 只会在字符串中出现一次。

最佳答案

您需要正则表达式才能使用 lookahead在这里。

test(?:\w|\s(?!test))+?follow

(?:) 是非捕获组。 \w 匹配任何单词字符 [a-zA-Z0-9_]\s 匹配任何空格(包括换行符)。 \s(?!test) 仅匹配后面没有 test 的换行符(在正则表达式中称为负向先行)。 ()+? 只是使匹配非贪婪。

通过匹配测试输入:

test
word
**test**
**word**
**follow**
word
test
**test**
**word**
**word**
**follow**
word
word
**test**
**word**
**follow**

<小时/>以下正则表达式也消除了任何子字符串匹配(例如测试中的测试、抗议等)。

(?<!\w)(test)\s(?!\1\s)(?:\w|\s(?!\1\s))*?(?<!\w)follow(?!\w)

关于python - 正则表达式用于匹配不具有相同单词出现在另一个关键字之前的关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19184192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com