是否能用正则实现判断一段字符串中包含某个子串且不包含另一个子串?
问题描述:
就是一段字符串要同时满足这两个条件才能匹配上:
1、包含“abc”或“def”
2、不包含“gh”
这种有办法用正则实现吗?
答
^(?!.*gh).*(abc|def)
答
直接用字符串函数不就行了,
答
正则很强大,你这需求肯定能实现的
答
用字符串函数吧。正则表达式在这个上面用起来不是很方便,但是可以实现
答
- 常见函数 strstr($str, "abc"); 2. 正则匹配 preg_match("/(abc)/is", $str); 但是要匹配一个字符串中,不包含某字符串,用正则就比较麻烦了。
- 如果不用正则如下就可以解决问题 !strstr($str, "abc"); 2. 但是用正则呢,就只有这样了 preg_match("/^((?!abc).)*$/is", $str); 完整代码示例 $str = "dfadfadf765577abc55fd"; $pattern_url = "/^((?!abc).)*$/is"; if (preg_match($pattern_url, $str)) { echo "不含有abc!"; } else { echo "含有abc!"; } 结果为:false,含有abc!
答
上面写错^((?!gh).)*abc((?!gh).)*$
答
完整写法^((?!gh).)*(abc|def)((?!gh).)*$
答
indexof() == -1 代表不包含
答
^((?!.*gh).)*(abc|def) .*$
测试三段:
1. I like abc
2. I like def
3.I like abc and gh
答
修正:(之前多了个空格)
^((?!.*gh).)*(abc|def).*$
测试三段:
1. I like abc
2. I like def
3.I like abc and gh