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.
|
|---|
| 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 | |
by haukex (Archbishop) on Aug 17, 2017 at 13:25 UTC |