Regex 正则表达式替换匹配的组内容?
我有正则表达式:Regex 正则表达式替换匹配的组内容?,regex,Regex,我有正则表达式: (a+)(,)(b+) 正在分析字符串:aaaa,bbb 对我来说,让团队保持1美元、2美元、3美元是非常重要的。 我需要一个正则表达式用法(仅,无Js、c#等),它将为我提供: kkkk,ppp 流量: 1) emit group1 , group2 , group3 2) keep the $2 group 3)replace the 'a' to 'k' ( as many as 'a'.count) 3)replace the 'b' to 'p' ( as m
(a+)(,)(b+)
正在分析字符串:aaaa,bbb
对我来说,让团队保持1美元、2美元、3美元是非常重要的。
我需要一个正则表达式用法(仅,无Js、c#等),它将为我提供:
kkkk,ppp
流量:
1) emit group1 , group2 , group3
2) keep the $2 group
3)replace the 'a' to 'k' ( as many as 'a'.count)
3)replace the 'b' to 'p' ( as many as 'b'.count)
编辑
在Js中替换(regexp/substr,newstring)我没有问题
但是我不想要任何循环或类似的东西。正则表达式是一种模式匹配机制。您要求的是更换图案。这可以通过不同语言的其他语言构造来实现,但不能通过正则表达式本身实现。由于您明确排除了任何语言细节,因此您的问题没有答案 编辑: 好的,现在您已经编辑了您的问题并允许特定语言的解决方案。请参阅Ed的答案。尝试以下方法:
str.replace(
new RegExp("([ab]+)", "g"),
// Here, we are passing in a nameless function as the parameter for
// the "replace" argument of the String Replace method. It uses the $1
// to refer to the grouping of a or b.
function($1){
if ($1.charAt(0) == "a"){
// replace with k
return( $1.replace(/./g, "k") );
} else {
// replace with p
return( $1.replace(/./g, "p") );
}
}
)
根据您自己的需要进行调整。抱歉,不能仅使用正则表达式。您可以使用perl/preg\u replace\u回调来执行此操作,但这不是“regex”,因为这两个版本都在替换函数中执行代码。@FailedDev我对
string.replace(regexp/substr,newstring)没有问题
在Js中,但我不想要任何循环或类似的东西。您不需要指定语言-检查@Ed的答案以获得简单的perl方法。@Royi:对于使用string.replace的JavaScript,我担心在这些限制下无法完成。@FailedDev这是我的测试环境。我不想在那里找到解决办法。这就是所需要的:aaaa,bbb.replace(新的RegExp(((a+)(,)(b+),(g)),函数($1,$2,$3,$4){返回($2.replace(/a/gi,'k')+$3+$4.replace(/b/gi,'p'))