【问题标题】:Is there a way to replace a substring with a same amount of X characters the length of it?有没有办法用长度相同的 X 字符替换子字符串?
【发布时间】:2015-06-23 15:45:54
【问题描述】:

我正在尝试使用 Perl 使用正则表达式匹配文件中的某些字符串,该正则表达式将用等量的 X 字符替换它们,就像原始字符串长度一样。 例如,该文件可能包含以下内容:

"the quick brown hello world fox jumps over the world" etc. etc.

还有一个字典,例如有这样的字符串:"hello world",我之前会加载到一个数组中。

我希望得到以下结果:

"the quick brown XXXXX XXXXX fox jumps over the world" etc. etc.

【问题讨论】:

  • 根据您的用例,请不要忘记阅读此内容:blog.codinghorror.com/…
  • 你应该用请求的编程语言标记你的问题
  • 你需要设计算法......获取数组中的所有字典单词。创建字典副本,并将所有字符替换为 X(不是空格)。对字典中的每个单词( strpos() )进行循环测试,如果找到,则用屏蔽字符串(str_replace)替换。
  • @rubenrp81 “标记你的问题”?
  • 你的语言是php?

标签: regex perl


【解决方案1】:

没有。

但是,您的语言可能有一个接受回调的正则表达式替换函数。然后你可以这样做:

>>> re.sub(r'o+b', lambda m: 'x' * len(m.group(0)), 'foobar')
'fxxxar'

【讨论】:

  • “否。”我挑战那个解决方案
【解决方案2】:

您可以使用带有/e 修饰符的替换来替换表达式,以及重复运算符x

代码如下所示。 \Q ... \E 构造用于转义任何非字母数字字符,以便将它们按字面解释而不是正则表达式元字符

use strict;
use warnings;
use 5.010;

my $s = 'the quick brown hello world fox jumps over the world';

my $pattern = 'hello world';

$s =~ s/(\Q$pattern\E)/'X' x length $1/e;

say $s;

输出

the quick brown XXXXXXXXXXX fox jumps over the world

更新

如果你想在被替换的字符串中保留空格,那么你需要两个嵌套的表达式替换,像这样

use strict;
use warnings;
use 5.014;

use Data::Dump;

my $s = 'the quick brown hello world fox jumps over the world';

my $pattern = 'hello world';

$s =~ s{(\Q$pattern\E)}{ s/(\S+)/'x' x length($1)/egr }e;

say $s;

输出

the quick brown xxxxx xxxxx fox jumps over the world

或者,如果您运行的是非常旧的 Perl 版本(v5.14 之前),那么您需要这个

$s =~ s{(\Q$pattern\E)}{ (my $r = $1) =~ s/(\S+)/'x' x length($1)/eg; $r }e;

【讨论】:

  • @tent:如果您要替换英文单词,那么您可能希望至少将您的正则表达式包装在\b...\b(伤口边界锚)以避免尴尬
  • 你的意思是这样的吗:$s =~ s/(\b\Q$pattern\E\b)/'X' x 长度 $1/e;因为它们总是在边界内并且永远不会嵌套。顺便说一句:是否可以在多行之间进行匹配(我将从包含多行和模式的文件中读取 $s可能会出现换行但总是只出现在空格上)
  • @tent:是的。我在想s/\b(\Q$pattern\E)\b/'X' x length $1/e,但你的很好
  • 顺便说一句:是否可以在多行之间进行匹配(我将从包含多行的文件中读取 $s 并且该模式可能会出现换行但总是仅在空白处)
  • @tent 你必须在模式中使用\s+ 而不是空格
【解决方案3】:

不如 ThiefM 的答案优雅(Python):

import re
str_to_replace = 'hello world'
print re.sub(str_to_replace, re.sub('\w', 'x', str_to_replace), \
    "the quick brown hello world fox jumps over the world")

# another option 
print "the quick brown hello world fox jumps over the world".replace(str_to_replace, re.sub('\w', 'x', str_to_replace))

输出

the quick brown xxxxx xxxxx fox jumps over the world

@rubenrp81 的 PHP 解决方案:

<?php
$msg = "the quick brown hello world fox jumps over the world";
$str = "hello world";
$rep = preg_replace("/\w/", "x", $str);
$patt = "/$str/";
$res = preg_replace($patt, $rep, $msg);
echo $res; // prints: "the quick brown xxxxx xxxxx fox jumps over the world"
?>

【讨论】:

  • @rubenrp81 这是python。顺便说一句,你怎么断定它是 PHP 的?
  • @rubenrp81 LOL,这里有一个 PHP 解决方案给你 ;)
猜你喜欢
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多