需要将文本文件中出现的字符串"gotcha“转换为gotcha[1]、gotcha[2]、gotcha[3]等(按顺序)。
我可以用一个简单的C++程序很容易做到这一点,但我想知道是否有更简单的方法。在我的文本编辑器中,Regex-replace似乎不能使用。在网上冲浪之后,看起来Perl、sed或awk可能是合适的工具,但我对这些工具都不熟悉。
发布于 2013-04-28 03:27:30
我不知道其他语言是否支持这个功能,但是在PHP中有e修饰符,这个修饰符当然不好用,而且在最近的PHP版本中已被弃用。这是一个用PHP写的POC:
$string = 'gotcha wut gotcha wut gotcha wut gotcha PHP gotcha rocks gotcha !!!'; // a string o_o
$i = 0; // declaring a variable i which is 0
echo preg_replace('/gotcha/e', '"$0[".$i++."]"', $string);
/*
+ echo --> output the data
+ preg_replace() --> function to replace with a regex
+ /gotcha/e
^ ^--- The e modifier (eval)
--- match "gotcha"
+ "$0[".$i++."]"
$0 => is the capturing group 0 which is "gotcha" in this case"
$i++ => increment i by one
Ofcourse, since this is PHP we have to enclose string
between quotes (like any language :p)
and concatenate with a point: "$0[" . $i++ . "]"
+ $string should I explain ?
*/Online demo。
当然,由于我知道有一些讨厌的人,所以我将向您展示在PHP语言中没有e修饰符的正确方法,让我们使用preg_replace_callback!
$string = 'gotcha wut gotcha wut gotcha wut gotcha PHP gotcha rocks gotcha !!!';
$i = 0;
// This requires PHP 5.3+
echo preg_replace_callback('/gotcha/', function($m) use(&$i){
return $m[0].'['.$i++.']';
}, $string);Online demo。
发布于 2013-04-28 02:59:57
在红宝石中
count = 0
"gotcha gotcha gotcha".gsub(/(gotcha)/) {|s| count+=1; s + "[" + count.to_s + "] ";}输出:
=> "gotcha[1] gotcha[2] gotcha[3] "但这是ruby特有的方式。
了解您想要使用的语言将有助于获得特定于语言的解决方案。
发布于 2013-04-28 03:29:12
在python中,它可以是:
import re
a = "gotcha x gotcha y gotcha z"
g = re.finditer("gotcha", a)
for i, m in reversed(list(enumerate(g))):
k = m.end()
a = '{}[{}]{}'.format(a[:k], i, a[k:])
print a当然,您可以将所有内容都塞到一行中(出于节省垂直空间的更高目的)
https://stackoverflow.com/questions/16255549
复制相似问题