在某些正则表达式中,不支持[负]零宽度断言(前瞻/后仰)。
这使得非常困难(不可能)声明排除。例如“每一行都没有”foo“就可以了,就像这样:
- ^((?!foo).)*$
可以实现同样的事情,而不必使用周围的环境(复杂性和性能问题暂时搁置一边)?
- ^(f(o[^o]|[^o])|[^f])*$
注意:在客户端上否定匹配而不是使用上述正则表达式,要容易得多。
正则表达式假设每行以一个换行符结尾,如果它不是看到C和grep的正则表达式。
Perl,Python,C和grep中的示例程序都提供相同的输出。
> perl
- #!/usr/bin/perl -wn
- print if /^(f(o[^o]|[^o])|[^f])*$/;
> python
- #!/usr/bin/env python
- import fileinput,re,sys
- from itertools import ifilter
- re_not_foo = re.compile(r"^(f(o[^o]|[^o])|[^f])*$")
- for line in ifilter(re_not_foo.match,fileinput.input()):
- sys.stdout.write(line)
> c
- #include <iostream>
- #include <string>
- #include <boost/regex.hpp>
- int main()
- {
- boost::regex re("^(f(o([^o]|$)|([^o]|$))|[^f])*$");
- //NOTE: "|$"s are there due to `getline()` strips newline char
- std::string line;
- while (std::getline(std::cin,line))
- if (boost::regex_match(line,re))
- std::cout << line << std::endl;
- }
> grep
- $ grep "^\(f\(o\([^o]\|$\)\|\([^o]\|$\)\)\|[^f]\)*$" in.txt
示例文件:
- foo
- 'foo'
- abdfoode
- abdfode
- abdfde
- abcde
- f
- fo
- foo
- fooo
- ofooa
- ofo
- ofoo
输出:
- abdfode
- abdfde
- abcde
- f
- fo
- ofo