0

我想删除小数点之后的所有内容,包括小数点后的所有内容,以及除连字符以外的所有非数字内容(如果它是第一个字符)。到目前为止,我有这个:/[^0-9^-]|[^\.]+$/。请注意我是如何阻止用 删除破折号的^-,因为不知何故我只想删除不是第一个字符(不是符号)的破折号。有什么帮助吗?谢谢。

我只是想让它删除

  • 任何非 0-9 字符,第一个字符除外,如果它是破折号(负号)
  • 包括小数点之后的所有内容

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

编辑:没关系,我以错误的方式接近这个,试图匹配不属于的字符,我意识到我不应该为此使用正则表达式。不过,感谢您的回答,我对正则表达式有所了解,也许其他有类似问题的人会发现这一点。

4

2 回答 2

2

试试这个:

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));
}

或者这个:

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

或者这个:

var re = /^(-?\d*)[^0-9]*(\d*)\.([\s\S]*?)$/
alert(parseInt("10js-_67.09090FD".replace(re, "$1$2"),10));
于 2009-10-23T02:14:50.233 回答
1

那将是/^(-?[0-9]+)[^0-9\.]*([0-9]*).*$/\1\2/(用于 sed,因为您没有告诉我您使用的是什么语言)。

/^(-?[0-9]+)[^0-9\.]*([0-9]*).*$/
// '^'          ==>l From the Start
// '(..)'       ==>l Group 1
//     '-?'     ==>l An optiona '-'
//     '[0-9]+' ==>l Some numbers
// '[^0-9\.]*'  ==>l Anything but numbers and dot
// '(..)'       ==>l Group 2 (So this is the number after the dot)
//     '[0-9]*' ==>l Some numbers
// '.*$'        ==>l The rest

然后只打印第 1 组和第 2 组 (/\1\2/)。

测试:

$:~/Desktop$ echo "10js-_67.09090FD" | sed -r "s/^(-?[0-9]+)[^0-9\.]*([0-9]*).*$/\1\2/"
1067
$:~/Desktop$ echo "-10a.h96" | sed -r "s/^(-?[0-9]+)[^0-9\.]*([0-9]*).*$/\1\2/"
-10

希望这可以帮助

于 2009-10-23T02:18:02.847 回答