[newbie] regexp question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • grikdog
    New Member
    • Mar 2007
    • 3

    [newbie] regexp question

    How do I write a regexp that will select 1.23 or -12.34 but not 1.2.3?

    $a =~ s/(\-*\d+\.\d+)/foo\1bar/g;

    This always selects 1.2 out of 1.2.3, and it should not. I.e., "foo1.2bar. 3" is an error.

    Thanks!
  • numberwhun
    Recognized Expert Moderator Specialist
    • May 2007
    • 3467

    #2
    Maybe its because its after midnight and I have been coding all day, who knows, but I am not really sure what you are wanting to do.

    That aside though, I took and modified your regex (only slightly), at the behest of the Komodo editor that I am using. Here is the quick script I wrote:

    Code:
    use strict;
    use warnings;
    
    print("Please input a string: ");
    my $input = <STDIN>;
    chomp($input);
    
    $input =~ s/(\-*\d+\.\d+)/foo$1bar/g;
    
    print("$input");
    Now, I ran the script a few times, using the input you provided. You can see here what the script produced:

    ######## Script Output ############

    C:\>perl select.pl

    Please input a string: foo1.2bar.3
    foofoo1.2barbar .3

    C:\>perl select.pl

    Please input a string: 1.2.3
    foo1.2bar.3

    C:\>perl select.pl

    Please input a string: 1.23
    foo1.23bar

    C:\>perl select.pl

    Please input a string: -12.34
    foo-12.34bar

    C:\>

    ######## End Output #############

    I addeed blank lines here manually for readability of the output. As you can see, I think it did what you wanted, but again, I wasn't quite sure what you were looking for.

    If this isn't what you wanted, maybe you could elaborate a fair amount and provide better examples of what you are trying to achieve.

    Regards,

    Jeff

    Comment

    • miller
      Recognized Expert Top Contributor
      • Oct 2006
      • 1086

      #3
      I also do not know what you're ultimately trying to acheive. However, the following faq link will probably be helpful in some way.

      perldoc perlfaq4 How do I determine whether a scalar is a number/whole/integer/float?

      - Miller

      Comment

      • KevinADC
        Recognized Expert Specialist
        • Jan 2007
        • 4092

        #4
        you never told the regexp where to stop substituting, you only gave it part of a pattern to find and replace. If you don't want the rest of the patter/string included on the replacement side you have to add it to the search pattern and exclude it in the replacement pattern.

        Code:
        $a = '1.2.3';
        $a =~ s/(\-?\d+\.\d+)(?:\.\d)/foo\1bar/;
        print $a;
        adding (?:\.\d) after the search pattern and not carrying it over to the replacement pattern (using $2 or \2) prevents the regexp from including that part of the string in the replacement pattern.

        Comment

        Working...