简体   繁体   English

正则表达式替换匹配的组内容?

[英]Regex replace matched Group content?

I have the regex : 我有正则表达式:

(a+)(,)(b+)

which is anallyzing the string : aaaa,bbb 正在分析字符串: aaaa,bbb

It is very important for me to keep the group $1 , $2, $3. 对我来说,保持组$1 , $2, $3.至关重要$1 , $2, $3.

I need a Regex usage( only , no Js , c# etc) which will giv me this : 我需要一个正则表达式用法( ,没有Js,c#等),这将给我以下信息:

kkkk,ppp

flow : 流 :

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)

edit 编辑

I dont have problem to string.replace(regexp/substr,newstring) in Js 我在Js中对string.replace(regexp/substr,newstring)没有问题

But I dont want any loops or someting like that. 但是我不想要任何循环或类似的东西。

Try this : 尝试这个 :

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") );
      }
   }
)

Adjust it to your own needs. 根据您的需要进行调整。

Regular expressions are a pattern matching mechanism. 正则表达式是一种模式匹配机制。 What you are asking for is pattern replacement. 您要的是图案替换。 This is possible by additional language constructs that differ from language to language, but not by regex itself. 这可以通过不同语言的其他语言构造来实现,但不能通过正则表达式本身来实现。 As you expressly exclude any language specifics, there is no answer to your question. 由于您明确排除任何语言细节,因此您的问题没有答案。

Edit: 编辑:

Ok, now you have edited your question and allow language specific solutions. 好的,现在您已经编辑了问题,并允许使用特定于语言的解决方案。 See Ed's answer. 请参阅Ed的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM