in reply to Reg exp questions

UPDATE: I originally misread the question... I thought the OP wanted to replace |, but the OP really wants to replace ().

\s should not be used in the REPLACEMENT part of s///

use warnings; use strict; my $str = 'a|b|c d e '; $str =~ s/[\s|]/_/g; print "$str\n"; $str = "w\nx\ny\nz"; $str =~ s/\n/ /g; print "$str\n"; __END__ a_b_c_d____e__ w x y z

Here is an explanation of your 1st regex (Tip #9 from the Basic debugging checklist):

The regular expression: (?-imsx:\s|\(|\)) matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- \s whitespace (\n, \r, \t, \f, and " ") ---------------------------------------------------------------------- | OR ---------------------------------------------------------------------- \( '(' ---------------------------------------------------------------------- | OR ---------------------------------------------------------------------- \) ')' ---------------------------------------------------------------------- ) end of grouping ----------------------------------------------------------------------

Replies are listed 'Best First'.
Re^2: Reg exp questions
by carolw (Sexton) on Nov 07, 2014 at 19:27 UTC

    and if I have one space before the end of the $str and one (, one ), this doesn't work with or without / for ()

    $str =~ s/()[\s]/_/;
      Show your exact input strings, and your expected output strings. http://sscce.org

        my $str = 'dfsldjf(djfls)jfslfk kfds\nfjsldf';

        output: dfsldjf_djfls_jfslfk_kfds fjsldf

Re^2: Reg exp questions
by carolw (Sexton) on Nov 08, 2014 at 19:33 UTC

    How to combine the expressions? for ex, if I want to replace ()[] by the same char, how to can i combine it?

    $str =~ s/()[]/"/g;

      Quoting is in M$Win style:

      C:\>perl -E "my $str='abc()[]xyz'; $str =~ s/[()\[\]]{1}/\"/g; say $st +r; abc""""xyz

      IOW, use a character class and escaping; both of which can be found in perldoc's perlre* pages. Note that the quantifier is redundant here, but could be useful were you trying to substitute two-at-a-time. OTOH, the /g modifier is NOT optional for this use case.

      C:\>perl -E "my $str='a)bc([]xyz'; $str =~ s/[()\[\]]{2}/\"/g; say $st +r; a)bc"]xyz

      ++$anecdote ne $data