如何找到前面没有另一个特定单词的单词? [英] How to find a word NOT preceded by another specific word?

查看:53
本文介绍了如何找到前面没有另一个特定单词的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用哪个正则表达式来查找所有字符串 bar 前面没有字符串 foo?两者之间有空格也是非法的.

所以正则表达式应该匹配以下字符串

foo 是 bar你好酒吧

但不是这些

foobar富吧

我尝试使用以下内容

(?!

它完成了消除foobar的工作,但我需要处理空格,当然

(?!

匹配所有字符串.

谢谢!

解决方案

最好使用编程语言的其他工具,而不是对正则表达式模式过于费力.

您正在寻找 $s =~/bar/而不是 $s =~/foo\s*bar/ 为真的字符串.

以下脚本的其余部分仅用于测试.

#!/usr/bin/perl使用严格;使用警告;我的 %strings = ('foo is bar' =>1、'你好酒吧' =>1、'foobar' =>0,'foo bar' =>0,'barbar' =>1、'bar foo' =>1、'foo foo' =>0,);我的@accept = grep { $strings{$_} } 键 %strings;我的@reject = grep { 不是 $strings{$_} } 键 %strings;对于我的 $s (@accept) {if ( $s =~/bar/而不是 $s =~/foo\s*bar/) {打印好:$s\n";}别的 {打印坏:$s\n";}}对于我的 $s (@reject) {if ( $s =~/bar/而不是 $s =~/foo\s*bar/) {打印坏:$s\n";}别的 {打印好:$s\n";}}

输出:

<前>E:\srv\unur> j好:酒吧富好:你好酒吧好:foo 是酒吧好:酒吧好: foo foo好: foo 酒吧好: foobar

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!

解决方案

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.

#!/usr/bin/perl

use strict; use warnings;

my %strings = (
    'foo is bar'  => 1,
    'hello bar'   => 1,
    'foobar'      => 0,
    'foo     bar' => 0,
    'barbar'      => 1,
    'bar foo'     => 1,
    'foo foo'     => 0,
);

my @accept = grep { $strings{$_} } keys %strings;
my @reject = grep { not $strings{$_} } keys %strings;

for my $s ( @accept ) {
    if ( $s =~ /bar/ and not $s =~ /foo\s*bar/ ) {
        print "Good: $s\n";
    }
    else {
        print "Bad : $s\n";
    }
}

for my $s ( @reject ) {
    if ( $s =~ /bar/ and not $s =~ /foo\s*bar/ ) {
        print "Bad : $s\n";
    }
    else {
        print "Good: $s\n";
    }
}

Output:

E:\srv\unur> j
Good: bar foo
Good: hello bar
Good: foo is bar
Good: barbar
Good: foo foo
Good: foo     bar
Good: foobar

这篇关于如何找到前面没有另一个特定单词的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆