mIRC Home    About    Download    Register    News    Help

Print Thread
Replacing a specific occurence #127843 17/08/05 11:05 AM
Joined: Mar 2005
Posts: 20
E
Erebus Offline OP
Ameglian cow
OP Offline
Ameglian cow
E
Joined: Mar 2005
Posts: 20
If I have a number of occurences of a substring in a string, is there any way I can replace a specific occurence, rather than all occurences.

I have tried everything, but as of yet I have not found a way to accomplish this.

For example, if I have the string 'testabtestabtestab' and want to replace the second occurence of 'ab' with 'ing' but none of the others, how could I do this? If possible, a general way that can be applied to different strings and substrings.

I would aprecaite any help,

Thanks a lot.

Re: Replacing a specific occurence #127844 17/08/05 11:36 AM
A
Anonymous
Unregistered
Anonymous
Unregistered
A
pass through the string searching for the n occurence. once you found it, remeber the index of the first letter of the pattern (in the string).

pass again through the string and replace the pattern with your text (begining with the caracter at the index position).

Re: Replacing a specific occurence #127845 17/08/05 11:55 AM
Joined: Mar 2005
Posts: 20
E
Erebus Offline OP
Ameglian cow
OP Offline
Ameglian cow
E
Joined: Mar 2005
Posts: 20
Thanks a lot for the reply,

How exactly should I go about doing this? I'm not certain I follow what you mean

Thanks.

Re: Replacing a specific occurence #127846 17/08/05 12:18 PM
Joined: Apr 2003
Posts: 701
K
Kelder Offline
Hoopy frood
Offline
Hoopy frood
K
Joined: Apr 2003
Posts: 701
Place this in your remotes tab (alt-r twice):
Code:
; $1 = text, $2 = substring, $3 = occurrence number, $4 = replacement
; example: $onesubst(ffabcabdabeabf,ab,3,__) returns ffabcabd__eabf
alias onesubst {
  var %3 = $3 - 1, %2 = $+(\Q,$replacecs($2,\E,\E\E\Q),\E)
  var %re = ^((?:.*? $+ %2 $+ ){ $+ %3 $+ }.*?) $+ %2
  var %res, %4 = $replace($4,\,\\), %u = $regsub($1,%re,\1 $+ $4, %res)
  echo -s 3: %3 ,2: %2 ,4: %4 ,re: %re ,u: %u
  return %res
}

//Echo -s $onesubst(testabtestabtestab,ab,2,ing)
testabtestingtestab