Reputation: 2336
I've a list of strings of the following type:
27 km 56.1 km 45 KM 96.2km 87 k
And I want to get the numeric value for each one. As you can see some of them are float values, and the suffix "km" sometimes is mistyped. The output I'm looking for is the following:
27 56.1 45 96.2 87
I've found regular expressions on the web that convert a string to number but they don't consider that some values can be float, how can I write a function or find a expression that meets my requirements?
Upvotes: 1
Views: 4359
Reputation: 1
try this. works for me
try {
Regex regexObj = new Regex(@"\b\d+(?:\.\d{0,}|)");
Match matchResults = regexObj.Match(subjectString);
while (matchResults.Success) {
// matched text: matchResults.Value
// match start: matchResults.Index
// match length: matchResults.Length
matchResults = matchResults.NextMatch();
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
php way
preg_match_all('/\b\d+(?:\.\d{0,}|)/', $subject, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
# Matched text = $result[0][$i];
}
Upvotes: 0
Reputation: 91762
No need for a regex, just use floatval
:
$float = floatval($string);
Upvotes: 4
Reputation: 12983
Just parseFloat()
them. parseFloat()
converts strings that start with a number to a number and stop with the first non-numeric character.
parseFloat('96.2 km')
= 96.2
Upvotes: 2