MOO-cows Mailing List Archive

[Prev][Next][Index][Thread]

Re: regex substitution



>>What I want to do is take an arbitrary string and substitute one
>>string for arbitrary substrings.  For example, substitute an 's' or
>>any number of 's's with the letter 't'.  Using sed, I'd just do a
>>s/ss*/t/ or s/s+/t/ (I think).  I'm going to be substituting in arbitrary
>>text, though, so I don't have the luxury of marking my substitutions
>>with %'s.
>
>Oh, I see:
>
>;strsub("What the fuck is STRSUB???","fuck","fudge")
>=> "What the fudge is STRSUB???"
>
>- Kipp

that's what I was going to answer also, but the question was how could you
substitute using regexps: you can only use strsub() to substitute fixed strings.

Let's take the example that was provided: replacing one or more consecutive
s's with the letter 't'. As you know, the regexp to match s's is "s+". But
since match() returns the index numbers of the matched string.. all you'd
have to do was use those numbers to change the actual string.

;match=match("aaaaaasssssssbbbbb","s+")
=> {7, 13, {{0, -1}, {0, -1}, {0, -1}, {0, -1}, {0, -1}, {0, -1}, {0, -1},
{0, -1}, {0, -1}}, "aaaaaasssssssbbbbb"}

the first two numbers (7 and 13) are what you'd change the string to. So all
you'd have to do is
string(match[1]..match[2])="t"
and you'd have it changed. You'd probably have to make sure the match
passes, though.




Home | Subject Index | Thread Index