Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将文本regex中的单词替换为其他单词_Regex_Perl - Fatal编程技术网

将文本regex中的单词替换为其他单词

将文本regex中的单词替换为其他单词,regex,perl,Regex,Perl,我试图将所有单词“坏”替换为“好”,但有一个例外: 如果单词“太”在“坏”之前,“坏”不应改为“好”, “too”和“bad”之间可以有一个或多个空格,甚至html空格 所以在正则表达式操作之后,文本应该是 some text and some text too bad, some too  bad again some bad and other words bad, it is too bad 尝试了类似的操作,但无法正常工作 some text a

我试图将所有单词“坏”替换为“好”,但有一个例外:

如果单词“太”在“坏”之前,“坏”不应改为“好”, “too”和“bad”之间可以有一个或多个空格,甚至html空格

所以在正则表达式操作之后,文本应该是

some text and some text too bad,
some too  bad again some bad
and other words bad, it is too       bad 
尝试了类似的操作,但无法正常工作

    some text and some text too bad,
    some too  bad again some good
    and other words good, it is too       bad 

请帮助

我不相信使用正则表达式可以方便地实现这一点。它变得更加复杂,因为一个词的概念不清楚:例如,你想把“坏”当作“坏”这个词来对待

该程序将字符串标记为单词和分隔符,然后将所有出现的“bad”更改为“good”,除非前面有“too”(忽略大小写)。我已经在您的可能分隔符列表中包括了逗号、冒号和分号。您可能希望对此进行调整,以获得预期的结果

$text ~= s/(too(\s+|\s* \s*))bad/good/ig;

您可以尝试解码
html
空白,并应用一个正则表达式,该表达式计算前面的字符串是否也是

some text and some text too bad,
some too  bad again some good
and other words good, it is too       bad 
这将产生:

perl script.pl

尽管正则表达式专家可以创造奇迹,但最终还是需要有人理解和维护这样的代码。所以一个不可破坏的空间就变成了可破坏的?@Borodin:谢谢你注意到这个bug。我添加了
encode_entities()
函数来修复它。感谢Borodin和@Birei,它真的很有帮助
#!/usr/bin/env perl;

use strict;
use warnings;
use HTML::Entities;

while ( <DATA> ) { 
    _decode_entities($_, { nbsp => "\xA0" }); 
    s/(\w+)(\s+)bad/$1 eq 'too' ? $& : "$1$2good"/eg;
    encode_entities($_);
    print $_; 
}

__DATA__
some text and some text too bad,
some too&nbsp; bad again some bad
and other words bad, it is too       bad
perl script.pl
some text and some text too bad,
some too&nbsp; bad again some good
and other words good, it is too       bad