1

Im want to remove all but the float in this sting:

string = "1 south african rand is 0.11044"

Im doing it like this:

reg = /[^\d+.\d+]/g
console.log string.replace(reg, '')

that logs

10.11044

that is wrong, I want only the xxxx.xxxxx part. 1 is not a float so it should not be part of this?

How should I chage it?

Harry
  • 13,091
  • 29
  • 107
  • 167

7 Answers7

4

Try this instead

^((?!\d+\.\d+).)*

See this answer for more details: Regular expression to match a line that doesn't contain a word?

Community
  • 1
  • 1
Evan Knowles
  • 7,426
  • 2
  • 37
  • 71
2

Following regex should match floats for you (for the example provided):

/(-?\d*\.\d+)/

To replace:

console.log (string.replace(/(-?\d*\.\d+)/, ''));
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

I have used positive look behind (?<=..) in below regular expression

\.\d+(?<=\d)

Use this regular expression and replace below value with ''. The result will be 1 23 33 3

1 23 33.2000 3.4445

Hope it helps

SMS
  • 452
  • 2
  • 6
  • 1
    I think his desired result is `33.2000 3.4445`. `1` and `23` should be excluded because they don't have a decimal point and fraction. – Barmar Apr 16 '13 at 09:53
1
var reg = /\d+\.\d+/g
var str = "1 south african rand is 0.11044";
var onlyFloats = str.match(reg).join(" ");
console.log(onlyFloats)
user2264587
  • 484
  • 2
  • 6
0

Try this

string = "1 south african rand is 0.11044"
reg = /(\d+\.\d+)/g;
string.match(reg);
karthick
  • 11,998
  • 6
  • 56
  • 88
0
/**
 * @param $string
 * @return string
 * 
 * output
 * a.a.a.a.a.a.   => 0.0
 * 1.1.1.1.1.1.   => 1.11111
 * 2a$2.45&.wer.4 => 22.454 
 */
function stringToFlout($string) {
    $parts = explode('.', $string);

    for ($i = 0; $i < count($parts); $i++) {
        $parts[$i] = preg_replace('/[^0-9]/', '', $parts[$i]);
    }

    $left = $parts[0];
    if (empty($left))
        $left = 0;

    $float[] = $left;

    unset($parts[0]);
    $right = implode('', $parts);
    if (empty($right))
        $right = 0;

    $float[] = $right;

    return implode('.', $float);
}
apkmaker
  • 1
  • 1
0

I would use this regex:

(0|([1-9][0-9]*))?\.(0|([1-9][0-9]*))

The (0|([1-9][0-9]*))? matches an optional integer part, the \. matches dot, and the final (0|([1-9][0-9]*)) matches a mandatory fractional part. It succeeds for:

  • .5
  • 0.5
  • 0.0
  • 0.1
  • 0.5foo
  • 31.41592

It fails for:

  • 00.5
  • 100
  • nice
  • 2.

Anchored version:

^(0|([1-9][0-9]*))?\.(0|([1-9][0-9]*))$
Nirvana
  • 405
  • 3
  • 15