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

Hello I need to write a script using regular expressions that searches a string and adds a space before and after the operator. For example: $input = 123+54 The output needs to be 123 + 54 I'd be really grateful for some help.

Replies are listed 'Best First'.
Re: Reg exprs
by ww (Archbishop) on Mar 23, 2008 at 11:43 UTC

    Smells like homework!.

    If so, please label it... and consider that if you merely obtain an answer here without taking the trouble to learn how to do so for yourself, you're wasting your time, that of those who provide the answer, and all the resources being expended to "educate" you.

    <admonition> This is such a simple and basic question that that very asking implies an utter lack of effort to find the answer yourself.</admonition>

    So, hints only: See Chapter 9 of ISBN 0596001320, your textbook, almost any reputable introduction to Perl, or the answers in your computer, for which try perldoc -q regex which will provide a start. (No, that's deliberately NOT a direct link to a specific answer, but a moment or two of your time will lead you there.)

Re: Reg exprs
by linuxer (Curate) on Mar 23, 2008 at 13:59 UTC
    Hi,

    please have a look at http://perldoc.perl.org/perlrequick.html

    Keywords:
    - "Extracting Matches"
    - "Search and replace"

    Also helpful on regex:
    http://perldoc.perl.org/perlretut.html
    http://perldoc.perl.org/perlre.html

Re: Reg exprs
by Skeeve (Parson) on Mar 24, 2008 at 07:56 UTC

    ;-) Just that you have an answer ;-)

    my $input="123+45"; for ($input) { tr/ +/+ /; $_= join "+ +", split; tr/ +/+ /; } print $input;

    Now try to explain that!


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
      Here's another solution:
      my $input = '123+45'; my $output = ''; for ($input) { /\G ( \+ ) /xgc && do { $output .= " $1 "; redo }; /\G ( . ) /xgcs && do { $output .= $1; redo }; } print("$output\n");

      <hint>If only Perl had a substitution operator, this parser wouldn't be needed...</hint>

      The above assumes there's no spaces in input.
        No! It assumes there is no tab in the input. Space are preserved!

        s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
        +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: Reg exprs
by ysth (Canon) on Mar 24, 2008 at 04:38 UTC