elanghe has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to figure out how to do a replace on a string using a regular expression with a variable. The catch is, it should only perform the replace if the string has white space surrounding it. My current regex s/(\Q$user\E)/xxxxx/g is a bit too greedy and ends up replacing instances it shouldn't. An example would be if $user is lee I would want to replace any instance of lee but not lee in leeroy.
  • Comment on Regular Expression Help matching white space but not replacing it

Replies are listed 'Best First'.
Re: Regular Expression Help matching white space but not replacing it
by ikegami (Patriarch) on Aug 11, 2010 at 21:15 UTC

    If you count the start and end of the string as spaces,

    s/(?<!\S)\Q$user\E(?!\S)/xxxxx/g

    If $user is guaranteed to match /^\w/ and /\w\z/, and you're ok with loosening the requirement for spaces, the above can be simplified to

    s/\b\Q$user\E\b/xxxxx/g

    Update: Added first line to be clear.

      the word boundary seems to be just what I was looking for even if I didn't know exactly how to say it. Thanks
Re: Regular Expression Help matching white space but not replacing it
by JavaFan (Canon) on Aug 11, 2010 at 21:18 UTC
    I'd use:
    s/(\s)\Q$user\E(\s)/${1}xxxx${2}/;
    Note that this does as you define it: only replace it when surrounded by whitespace. It will not replace the user name if the name starts or ends the line.
      Thank you JavaFan. I must say that's much simpler than what I had been trying.