正则表达式:通过排除匹配,没有预见 – 有可能吗?

前端之家收集整理的这篇文章主要介绍了正则表达式:通过排除匹配,没有预见 – 有可能吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在某些正则表达式中,不支持[负]零宽度断言(前瞻/后仰)。

这使得非常困难(不可能)声明排除。例如“每一行都没有”foo“就可以了,就像这样:

  1. ^((?!foo).)*$

可以实现同样的事情,而不必使用周围的环境(复杂性和性能问题暂时搁置一边)?

  1. ^(f(o[^o]|[^o])|[^f])*$

注意:在客户端上否定匹配而不是使用上述正则表达式,要容易得多。

正则表达式假设每行以一个换行符结尾,如果它不是看到C和grep的正则表达式。

Perl,Python,C和grep中的示例程序都提供相同的输出

> perl

  1. #!/usr/bin/perl -wn
  2. print if /^(f(o[^o]|[^o])|[^f])*$/;

> python

  1. #!/usr/bin/env python
  2. import fileinput,re,sys
  3. from itertools import ifilter
  4.  
  5. re_not_foo = re.compile(r"^(f(o[^o]|[^o])|[^f])*$")
  6. for line in ifilter(re_not_foo.match,fileinput.input()):
  7. sys.stdout.write(line)

> c

  1. #include <iostream>
  2. #include <string>
  3. #include <boost/regex.hpp>
  4.  
  5. int main()
  6. {
  7. boost::regex re("^(f(o([^o]|$)|([^o]|$))|[^f])*$");
  8. //NOTE: "|$"s are there due to `getline()` strips newline char
  9.  
  10. std::string line;
  11. while (std::getline(std::cin,line))
  12. if (boost::regex_match(line,re))
  13. std::cout << line << std::endl;
  14. }

> grep

  1. $ grep "^\(f\(o\([^o]\|$\)\|\([^o]\|$\)\)\|[^f]\)*$" in.txt

示例文件

  1. foo
  2. 'foo'
  3. abdfoode
  4. abdfode
  5. abdfde
  6. abcde
  7. f
  8.  
  9. fo
  10. foo
  11. fooo
  12. ofooa
  13. ofo
  14. ofoo

输出

  1. abdfode
  2. abdfde
  3. abcde
  4. f
  5.  
  6. fo
  7. ofo

猜你在找的正则表达式相关文章