c# - RegExp: X number of matches => X number of replacements? -
using regular expressions i'm trying match string, has substring consisting of unknown number of repeats (one or more) , replace repeating substring same number of replacement strings.
if regexp "(st)[a]+(ck)", want these kind of results:
"stack" => "stock" "staaack" => "stooock" //so 3 times "a" replaced 3 times "o" "staaaaack" => "stooooock" how do that?
either c# or as3 do.
for as3 can pass function replace method on string object matching elements arguments array. can build , return new string 'a' replaced 'o'
for example:
// first way explicit loop var s:string="staaaack"; trace("before", s); var newstr:string = s.replace(/(st)(a+)(ck)/g, function():string{ var ret:string=arguments[1]; // here match 'st' //arguments[2] match 'aaa..' (var i:int=0, len:int=arguments[2].length; < len; i++) ret += "o"; return ret + arguments[3]; // arguments[3] match 'ck' }); trace("after", newstr); // output stoooock // second way array , join var s1:string="staaaack staaaaaaaaaaaaack stack paaaack" trace("before", s1) var after:string = s1.replace(/(st)(a+)(ck)/g, function():string{ return arguments[1]+(new array(arguments[2].length+1)).join("o")+arguments[3] }) trace("after", after) here live example on wonderfl : http://wonderfl.net/c/bowe
Comments
Post a Comment