views:

400

answers:

2

Removing everything after and including the decimal, and everything non-numerical except the dash if its in is the first character. So far I have this: /[^0-9^-]|[^\.]+$/. Notice How I block dashes from being removed with ^-, because somehow I want to only remove the dashes that aren't the first character (not the sign). Any help? Thanks.

I just want it to remove

  • Any non 0-9 characters, except the the first character if it is a dash (negative sign)
  • Everything after and including the decimal point

Ex.: 10js-_67.09090FD => 1067
-10a.h96 => -10

EDIT: Never mind, I was approaching this the wrong way, trying to match the characters that don't belong, and I realized I shouldn't be using a regex for this. Thanks for your answers though, I learned a bit about regex and maybe someone else with a similar problem will find this.

+2  A: 

Try this:

Regex numbers = new Regex(@"^(-?\d*)[^0-9]*(\d*)\.", 
    RegexOptions.ECMAScript | RegexOptions.Multiline);
foreach (Match number in numbers.Matches("10js-_67.09090FD"))
{
    Console.WriteLine(
        Int32.Parse(
            number.Groups[1].Value + 
            number.Groups[2].Value));
}

Or this one:

Console.WriteLine(
    Int32.Parse(
        Regex.Replace(
            "10js-_67.09090FD", 
            @"^(-?\d*)[^0-9]*(\d*)\.([\s\S]*?)$", "$1$2", 
            RegexOptions.ECMAScript | RegexOptions.Multiline)));

Or this one:

var re = /^(-?\d*)[^0-9]*(\d*)\.([\s\S]*?)$/
alert(parseInt("10js-_67.09090FD".replace(re, "$1$2"),10));
Rubens Farias
I'm using javascript.
Mk12
+1  A: 
NawaMan
I'm using javascript, and was using str.replace() to replace characters with "".
Mk12