怎么用正则表达式匹配指定字符串的前后5个字符内,排除指定字符?比如我想找一个字符串包含关键字“苹果”,但苹果的前后5个字符串内不能有“香蕉”关键字
香蕉苹果(不符合)
苹果香蕉(不符合)
香蕉zy苹果 (不符合)
香蕉zdfgjsdf苹果 (符合)
import re
r = re.search('.*[^香蕉]{5}(苹果)', '香蕉zdfgjsdf苹果').group(1)
print(r)
function match(str) {
return /(([^香蕉]{5})苹果([^香蕉]{5})|^([^香蕉]{0,4})苹果([^香蕉]{0,4})$|([^香蕉]{5})苹果$|^苹果([^香蕉]{5}))/g.test(str)
}
console.log(match('香蕉苹果香蕉')); // false
console.log(match('香蕉aaaaa苹果aaaaa香蕉')); // true
console.log(match('香蕉aaaa苹果aaaaa香蕉')); // false
console.log(match('香蕉aaaa苹果aaaa香蕉')); // false
console.log(match('香蕉aaaaa苹果')); // true
console.log(match('香蕉aaaa苹果')); // false
console.log(match('苹果aaaaa香蕉')); // true
console.log(match('苹果')); // true
console.log(match('aaa苹果')); // true
console.log(match('aaa苹果aaa')); // true
console.log(match('苹果aaa')); // true
console.log(match('苹果aaaaaa')); // true
console.log(match('aaaaaaaa苹果')); // true
([^香蕉][^香蕉][^香蕉][^香蕉][^香蕉]苹果(.+?){5})
^((?!(.*香蕉.{0,4}苹果.+)|(.*苹果.{0,4}香蕉.+)|(^[^(苹果)]+.$)).)*$
有一个问题: 前后五个字符串内不能有 "香蕉", 但是一个汉子是一个字符串吗?
博主参考下下面链接
https://b23.tv/AHCuQk5