# regex substitution

ThwartedEfforts (abakun@scinc.com)
Thu, 7 Mar 1996 07:50:51 PST

- Messages sorted by:[ date ][ thread ][ subject ][ author ]

    At 10:53 PM 3/6/96 PST, you wrote:
    >That's fine... what I *want* is this:
    >
    >;strsub("Can we be more patronizing?","mm*","b")
    >=> "Can we be bore patronizing?"
    >
    >but what I get is this:
    >
    >=> "Can we be more patronizing?"
    >
    >I have looked at the builtins and at $string_utils and it doesn't
    >look like anything does that.  I am curious if someone has written
    >something that does do this or if I'm missing something...

    You might want to stick this on your $string_utils:

    (I only write for 1.8 now :) Quick and dirty, as usual, of course.  But, of
    course, works like a charm, and in few ticks also.)

    @verb $string_utils:regexp_strsub
    @program $string_utils:regexp_strsub
    ":regexp_strsub ( STR <subject>, STR <regexp>, STR <new> )";
    "Returns <subject> with all occurances of <regexp> changed to <new>";
    {subject, regexp, new} = args;
    if ({typeof(subject), typeof(regexp), typeof(new)} != {STR, STR, STR})
      raise(E_INVARG);
    endif
    regexp = tostr("%(", regexp, "%)");
    while (matched = match(subject, regexp))
      if (typeof(matched) == ERR)
        raise(E_INVARG);
      endif
      if (!matched)
        return subject;
      endif
      if (subject[matched[1]..matched[2]] != "")
        subject[matched[1]..matched[2]] = new;
      endif
    endwhile
    return subject;

    (isn't this a builtin somewhere? weirdness in the making.)
    Then:

    ;$string_utils:regexp_strsub("Can we be more patronizing?","mm*","b")
    => "Can we be bore patronizing?"
    ;$string_utils:regexp_strsub("Can we be more patronizing?","xxxx","b")
    => "Can we be more patronizing?"

    You will, of course, be smart enough to not make <new> a subset of <regexp>,
    right? :)

    Hope that is what you need.  Hope you are running 1.8.  Enjoy.