Perl regex to extract floating number

前端 未结 3 955
情歌与酒
情歌与酒 2021-01-22 17:05

I need to modify someone\'s Perl script, and I am not familiar with Perl at all.

There is a scalar variable $var, whose value is a floating point number pos

相关标签:
3条回答
  • So I am trying suggested expressions, I guess I am not using them correctly in Perl:

    my $var = "123.456.66";
    print "old $var\n";
    $var =~ s/^\d+(?:\.\d+)?//;
    print "new $var\n";
    

    Output:

    $perl main.pl
    old 123.456.66
    new .66
    
    0 讨论(0)
  • 2021-01-22 17:48

    As I understand it, you need to extract the first one or two groups of digits from a string. Like so.

    123.456.789  # 123.456
    123.456abc   # 123.456
    123abc       # 123
    abc123       # nothing
    

    The regex would look like this, expanded out for a better explanation.

    qr{
      (
        \d+ 
        (?: \.\d+ )?
      )
    }x;
    

    qr is the regex quoting operator. Using x means to ignore spaces so things are more readable.

    \d matches digits. + says to match 1 or more of the preceding. So \d+ is 1 or more digits.

    () captures the contents.

    (?:) groups the contents but does not capture.

    ? says to capture 0 or 1 of the preceding. It means it's optional.

    So (?: \.\d+ )? means a dot followed by some digits is optional.

    You'd use it like so.

    my $str = "123.456abc";
    my $digits_re = qr{ (\d+ (?: \.\d+ )?) }x;
    my($digits) = $str =~ $digits_re;
    print $digits;
    

    For more information see the Perl Regex Tutorial and you can play with it on Regex 101.

    0 讨论(0)
  • 2021-01-22 17:54

    Following your update, the expression you need is:

    ^\d+(?:\.\d+)?
    
    • ^\d+ Match digits at start of string.
    • (?: Start of non capturing group.
    • \.\d+ Match a literal ., followed by digits.
    • )? Close non capturing group making it optional.

    Check the expression here.

    A Perl example:

    $var = "123.456.789";
    print "old $var\n";
    $var =~ /(^\d+(?:\.\d+)?)/;
    print "new $1\n";
    

    Prints:

    old 123.456.789
    new 123.456
    
    0 讨论(0)
提交回复
热议问题