题
在一些regex口味,[负面的]零宽度的断言(前瞻/查后面)均没有得到支持。
这使得极其困难(不可能的吗?) 国家一排斥。例如"每一条线, 不不 有"foo"上",是这样的:
^((?!foo).)*$
可以同样的事情,是实现没有使用你看-在所有(的复杂性和性能的问题搁置一边的时刻)?
解决方案
更新: 它失败"与两个ff前oo"为 @Ciantic指出的评论意见。
^(f(o[^o]|[^o])|[^f])*$
注: 这是很容易得多,只是为了否定的一匹配上的客户的身边,而不是使用上述regex.
Regex假定每个行结束一个行char如果这不是再见C++'s和查询的regexs.
采样方案在Perl,蟒蛇、C++、和 grep
所有得到相同的输出。
-
#!/usr/bin/perl -wn print if /^(f(o[^o]|[^o])|[^f])*$/;
-
#!/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 "^\(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
其他提示
遇到了这个问题,并采取了一个事实,即没有一个完全正常的工作正则表达式作为一个个人的挑战。我相信我已经成功地创建一个正则表达式是确实的所有投入工作 - 只要你能使用的原子分组 / 所有格量词的。
当然,我不知道是否有是的允许原子团,但不环视,但问题问是否有可能在正则表达式声明排除无环视,它的任何口味< EM>是技术上是可行的:
\A(?:$|[^f]++|f++(?:[^o]|$)|(?:f++o)*+(?:[^o]|$))*\Z
说明:
\A #Start of string
(?: #Non-capturing group
$ #Consume end-of-line. We're not in foo-mode.
|[^f]++ #Consume every non-'f'. We're not in foo-mode.
|f++(?:[^o]|$) #Enter foo-mode with an 'f'. Consume all 'f's, but only exit foo-mode if 'o' is not the next character. Thus, 'f' is valid but 'fo' is invalid.
|(?:f++o)*+(?:[^o]|$) #Enter foo-mode with an 'f'. Consume all 'f's, followed by a single 'o'. Repeat, since '(f+o)*' by itself cannot contain 'foo'. Only exit foo-mode if 'o' is not the next character following (f+o). Thus, 'fo' is valid but 'foo' is invalid.
)* #Repeat the non-capturing group
\Z #End of string. Note that this regex only works in flavours that can match $\Z
如果出于某种原因,你可以使用原子团,但不是占有量词也环视,你可以使用:
\A(?:$|(?>[^f]+)|(?>f+)(?:[^o]|$)|(?>(?:(?>f+)o)*)(?:[^o]|$))*\Z
正如其他人所指出的,虽然,它可能更实用,只是通过其他方式否定匹配。
可以通常寻找foo和倒置从客户端代码的正则表达式匹配的结果。
对于一个简单的例子,假设您想验证字符串只包含某些字符。
您可以写这样的:
^[A-Za-z0-9.$-]*$
和接受true
结果是有效的,或者是这样的:
[^A-Za-z0-9.$-]
和接受false
结果是有效的。
当然,这并不总是一个选项:有时也只能把表达在配置文件或将其传递到另一个程序,例如。但它是值得记住的。 您的具体问题,例如,表情的多的简单,如果你可以使用否定这样的。
我碰到这个问题,迷迷糊糊中的我正则表达式寻找我自己的正则表达式排除解决方案,其中我试图排除序列的。
我这种情况初始反应:例如foo“的在其上‘’不具有每行” 简单地使用匹配的grep选项的-v反相感
grep -v foo
这将返回一个文件中的所有行不匹配“富”
它是如此简单我有强烈的感觉,我只是误解你的问题....