By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,710 Members | 1,960 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,710 IT Pros & Developers. It's quick & easy.

Replacing the string

P: 37
Hello All,

I would like the replace the following string,

TRANS -847.0 -672.0 -71.0

as

TRANS -840.0 -660.0 -62.0

I am able to replace the string when the numbers are positive without decimals using \d and \s syntax. But the above expressions have negative sign and decimals. How could i formulate that using regexp.

Ramesh
Aug 5 '08 #1
Share this Question
Share on Google+
9 Replies


numberwhun
Expert Mod 2.5K+
P: 3,503
What have you tried thus far? I would love to see what you come up with and will then help you from there. Do not forget to post your code (in code tags) and any errors or results.

Regards,

Jeff
Aug 5 '08 #2

P: 37
Expand|Select|Wrap|Line Numbers
  1. #!\usr\bin\perl
  2. use warnings;
  3. use strict;
  4. open IN,"+< z.txt";  
  5. open OUT,"> t.txt";  
  6. while (<IN>) {
  7. s/(\d+)\s+(\d+)\s+(\d+)/ ($1+7).$2. ($3+12).$2.($4+9)/g;
  8. print OUT;
  9. }
This works when numbers are positive integers. My case is for decimals and negative numbers.
Aug 5 '08 #3

KevinADC
Expert 2.5K+
P: 4,059
Do not forget to post your code (in code tags)
oops...... hehehe
Aug 5 '08 #4

eWish
Expert 100+
P: 971
oops...... hehehe
Maybe numberwhun won't notice.
Aug 6 '08 #5

KevinADC
Expert 2.5K+
P: 4,059
Expand|Select|Wrap|Line Numbers
  1. my $str = 'TRANS -847.0 -672.0 -71.0';
  2. $str =~ s/(\S+)\s+(-?\d+\.?\d?)\s+(-?\d+\.?\d?)\s+(-?\d+\.?\d?)/sprintf "$1 %.1f %.1f %.1f", $2+7,$3+12,$4+9/eg;
  3. print $str;
Aug 6 '08 #6

P: 37
Thanks Kevin for the help. It replaces the negative and decimal numbers.
Aug 6 '08 #7

KevinADC
Expert 2.5K+
P: 4,059
Thanks Kevin for the help. It replaces the negative and decimal numbers.
Next time use the CODE tags, OK? If not, Jeff might ban you from the forum.
Aug 6 '08 #8

numberwhun
Expert Mod 2.5K+
P: 3,503
Next time use the CODE tags, OK? If not, Jeff might ban you from the forum.
I am not that cruel, I give a couple warnings. :-) Don't you have a rebellion to worry about Kevin?
Aug 6 '08 #9

KevinADC
Expert 2.5K+
P: 4,059
I am not that cruel, I give a couple warnings. :-) Don't you have a rebellion to worry about Kevin?

No, the rebellion was postponed, maybe cancelled, depends on if my wife comes to her senses.
Aug 6 '08 #10

Post your reply

Sign in to post your reply or Sign up for a free account.