我要删除一切之后,和包括小数,一切都非数字除了连字符的如果它的第一个字符。到目前为止,我有这样的: /[^0-9^-]|[^\.]+$/.注意到如何我框破折号被去除 ^-, 因为不知怎的,我希望仅删除线,这不是第一个字符的(不标志)。任何帮助吗?谢谢。

我只是希望它删除

  • 任何非0-9人物,除了第一字,如果它是一个破折号(负号)
  • 之后的一切和包括小数点

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

编辑:没关系,我是接近这种错误的方式,努力相匹配的字符,也不属于,我意识到我不应该使用regex这一点。谢谢你的答案,尽管,我学到一点关于regex也许有人别的有一个类似的问题将会发现这一点。

有帮助吗?

解决方案

试试这个:

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

其他提示

那将是 /^(-?[0-9]+)[^0-9\.]*([0-9]*).*$/\1\2/ (用于sed为你不告诉我是什么语言ar你使用).

/^(-?[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

希望这可以帮助

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top