in reply to Howto strip 42 from comma separated list using s///

Thanks guys, for all the input, suggestions and comments
I ended up with this regex:
((?=,*\s*42))(,\s*42|42\s*,|\s*42\s*)((?<=42\s*,*))
Apologies for not specifying up front all constraints of the problem. Though this specific regex has to be 'generic' in the sense that it must work in the .NET/C# environment, these kind of constraints often pop up (as anyone who has read "Mastering Regular Expressions" can testify). And looking at the problem from several angels is always educational and, well: fun.
Thanks
/ allan

Replies are listed 'Best First'.
Re^2: Howto strip 42 from comma separated list using s///
by pKai (Priest) on Dec 04, 2005 at 02:53 UTC
    ((?=,*\s*42))(,\s*42|42\s*,|\s*42\s*)((?<=42\s*,*))
    Being left with a result, which is not applicable in Perl isn't satisfying either. (There is no variable length lookbehind in Perl.)

    I tried to understand your regex without being able to test it (as given) in Perl. But I either did not get it, or it is still incomplete, as I have the impression, that a string like before,42XX,after will be reduced to beforeXX,after after applying your regex and substituting the match to empty??

    Anyway, I would suggest to use the regex provided by reasonablekeith earlier, because it seems to cover all cases correctly.

    Stripping enclosing whitespace is easily achieved with this too, by adjusting 42 to \s*42\s* (twice) in that regex.

      Well the regex did do the job in .NET (using $1$3 as replacement) on lists of the indicated type, like:
      "42,43" -> "43" "41,42" -> "41" "41,42,43" -> "41,43"
      That is: "42,15,42,173,42" will be reduced to "15,173", which was basically what I wanted. And yes, "before,42XX,after" will be reduced to "beforeXX,after", but that was not the kind of data I needed to manipulate in this case.

      You can try out .NET regexes by installing the runtime plus a tool like RegexDesigner.

      Update
      And you're right: the regex by reasonablekeith above does the same, but will leave "before,42XX,after" intact (if that's what you want); His regex is shorter tho', and could be preferred for that reason, -- but it is not forgiving with resp. to whitespace around the numbers, ie. "23,42 ,45, 56,42" will be reduced to "23,42 ,45, 56".

      Best regards,
      Allan Dystrup
Re^2: Howto strip 42 from comma separated list using s///
by Perl Mouse (Chaplain) on Nov 04, 2005 at 10:15 UTC
    Complicated. And I'm surprised - it seems that .NET/C# implements variable width look behind, something that Perl doesn't do.
    Perl --((8:>*