如何查找前面没有另一个特定单词的单词?
我可以使用哪个正则表达式来查找所有 bar
前面没有字符串 foo
的字符串?两者之间有空格也是非法的。
所以正则表达式应该匹配以下字符串,
foo is bar
hello bar
但不是这些
foobar
foo bar
我尝试使用以下字符串
(?!<foo)bar
,它完成了消除 foobar 的工作,但我需要处理空格,当然
(?!<foo)\s*bar
匹配所有琴弦。
谢谢!
Which regular expression can I use to find all strings bar
are not preceded by string foo
? Having whitespace between the two is also illegal.
So the regex should match the following strings
foo is bar
hello bar
But not these
foobar
foo bar
I've tried using the following
(?!<foo)bar
and it gets the work done for eliminating foobar
, but I need to take care of the whitespace, and of course
(?!<foo)\s*bar
matches all the strings.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最好使用编程语言的其他功能,而不是过于费力地寻找正则表达式模式。
您正在查找
$s =~ /bar/ 而不是 $s =~ /foo\s*bar/
为 true 的字符串。下面脚本的其余部分仅用于测试。
输出:
Better to use other facilities of the programming language than to look too hard for a regex pattern.
You are looking for strings for which
$s =~ /bar/ and not $s =~ /foo\s*bar/
is true.The rest of the script below is just for testing.
Output:
给定一些测试用例,
您当然可以通过将一种模式的结果提供给另一种模式来完成:
我们也可以用一个模式来完成:
但不要相信我的话。
Given a few test cases
you could of course do by feeding the results of one pattern to another:
We can also do it with one:
But don't take my word for it.
这将匹配空白
This will match the whitespace
php:
perl:
php:
perl:
从早期答案中获取信息,包装为 perl 单行代码,并使正则表达式不区分大小写。
Windows:
Linux:
xx.txt 包含:
在命令提示符处执行单行代码的结果:
Taking the information from earlier answers, wrapping as a perl one-liner, and making the regular expressions case-insensitive.
Windows:
Linux:
With xx.txt containing:
The result of executing the one-liner at a command prompt: