python - 如果某个单词之前的两个单词来自否定列表,如何使用正则表达式不匹配模式
问题描述
考虑下面的字符串:
str = "word1 word2 word3 word4 word5"
如果 word4 是来自 [sample1, sample2] 的样本并且 word2 不是来自 (sample3, sample4) 的样本,我想匹配一个模式。
例子:
str1 = "word1 word2 word3 sample1 word5" # it matches
str2 = "word1 sample3 word3 sample1 word5" # it doesn't match
我使用“Negative Lookbehind”编写了一个正则表达式,但我只能匹配一个单词之前而不是两个单词。
谢谢,如果有人可以帮忙。
解决方案
我想你正在寻找这样的正则表达式:
\w+ \w+(?<!sample3|sample4) \w+ (?:sample1|sample2) \w+
如果您遇到“固定模式长度”的一些问题,您可以通过这种方式使用负前瞻而不是后瞻:
\w+ (?!sample3|sample4)\w+ \w+ (?:sample1|sample2) \w+
因为在前瞻中没有限制。
推荐阅读
- amazon-dynamodb - DynamoDb 对使用 cloudformation 的多个表重新使用 ScalableTarget
- django - 代理模型 DRF/DJANGO 的序列化程序出现问题
- java - 具有单线程的 Java 线程池未按预期运行
- ruby - 第二列中 NMatrix 矩阵的水平串联不正确
- html - 如何在页面重新加载时保持选定的手风琴处于活动状态
- async-await - 使用期货从套接字列表中选择
- facebook - 为一个 Facebook 应用程序使用多个不同的域
- php - 支持mysql的php动态复选框
- javascript - 在海报加载之前强制播放视频
- javascript - 如何在范围内获得总和?