in reply to match digit, followed by hyphen, followed again by digit - then add whitespaces and replace in file

When I think "I need to match a number" I think of Regexp::Common::number, for example:

use warnings; use strict; use Regexp::Common qw/number/; use Data::Dump; #Debug while (<DATA>) { /^($RE{num}{decimal}\s*){4}$/ or die; my @cols = /$RE{num}{decimal}/g; dd @cols; #Debug } __DATA__ 1.234 5.6789 -1.235-4 1.234 5.6789-12.235-4

Which outputs:

(1.234, 5.6789, -1.235, -4) (1.234, 5.6789, -12.235, -4)

For an approach that is probably overkill for parsing something like this, see Re: How to split a non even number of string elements into a hash [RESOLVED].

Update: If you want to just rewrite the file, you can use the following oneliner, but note this will discard anything that doesn't match the regex! If you want to add validity checking, you could add /^($RE{num}{decimal}\s*){4}$/ or die; (which I have now added to the above example to make it more robust, although it's a little less efficient now since it matches each line twice).

$ perl -MRegexp::Common=number -nle '$,=" ";print/$RE{num}{decimal}/g' + input.txt >output.txt

Update 2: TIMTOWTDI, this inserts a space between two numbers that previously did not have a space between them (and it's a bit safer because inserting spaces should be all it does, instead of rewriting the entire lines):

$ perl -MRegexp::Common=number -pe 's/(?>$RE{num}{decimal})\K(?=$RE{nu +m}{decimal})/ /g' input.txt >output.txt

Sorry, this post also had a few ninja edits. OP msg'd.

  • Comment on Re: match digit, followed by hyphen, followed again by digit - then add whitespaces and replace in file (updated x2)
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: match digit, followed by hyphen, followed again by digit - then add whitespaces and replace in file
by fasoli (Beadle) on Aug 17, 2017 at 13:21 UTC
    This is brilliant! However the output now needs further formatting as it's printed with brackets etc. I tried adding a print statement but dd still prints everything. A bit confusing :(
      However the output now needs further formatting as it's printed with brackets etc. I tried adding a print statement but dd still prints everything.

      You can print @cols any way you want, using a regular print or printf, instead of Data::Dump, which is just a debugging aid. If you could show what code you are trying and what output format you expect, we could help better (How do I post a question effectively?). Also, note I updated my node right around the time you replied, check out the update too.