简体   繁体   中英

perl - regex for floating point number filter

I need to remove all characters not needed in a floating point number.

For example: 1). 12.23xf00 -> it should be 12.23 2). 15.0s-> it should be 15.0

I tried this:

sub retain_num_chars($) {
my $string = shift;
$string =~ (?:^|(?<=\s))[0-9]*\.?[0-9](?=\s|$);
return $string;
}
$string=~ retain_num_chars($string);

from Regex Matching numbers with floating point

but it returns an error: Unmatched ( in regex; marked by <-- HERE in m/:^|( <-- HERE

Thank you. I am really new in perl.

this will do your work :

(?=[^\d\.])(.*)

anything which is a non digit non decimal will be captured

you can replace it

?= means a positive lookahead, which means that what follows is a non digit non .

demo here : http://regex101.com/r/zH6jA8

There are several mistakes in your Perl code.

First is inside the function. I didn't see you doing any substitution operation over there using regex( s/// ) or whatever. Using the following two lines you can remove unwanted things from the number.

## assuming the format is ...dd.ddxxx
$string =~ s/^\s+(?=\d)//;  ## remove space from begin
$string =~ s/(\.\d+).*/$1/; ## removing other things after keeping the dot and digits

During the function call you are trying to assign using =~ operator which usually does regex matching. So change it into = .

$string = retain_num_chars($string);

Make use of the Abigail's Regexp::Common

use Regexp::Common;
...
... m/$RE{num}{real}/

怎么样:

$string =~ /(?<!\d)\d+(?:\.\d+)?(?!\d);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM