查找字符串中任何数字第一个出现的位置


Find the position of the first occurrence of any number in string

有人能帮我找到字符串中任何数字第一个出现的位置的算法吗?

我在网上找到的代码不起作用:

function my_offset($text){
    preg_match('/^[^'-]*-'D*/', $text, $m);
    return strlen($m[0]);
}
echo my_offset('[HorribleSubs] Bleach - 311 [720p].mkv');

内置的PHP函数strcspn()在使用时将与Stanislav Shabalin的答案中的函数相同:

strcspn( $str , '0123456789' )

示例:

echo strcspn( 'That will be $2.95 with a coupon.' , '0123456789' ); // 14
echo strcspn( '12 people said yes'                , '0123456789' ); // 0
echo strcspn( 'You are number one!'               , '0123456789' ); // 19

HTH

function my_offset($text) {
    preg_match('/'d/', $text, $m, PREG_OFFSET_CAPTURE);
    if (sizeof($m))
        return $m[0][1]; // 24 in your example
    // return anything you need for the case when there's no numbers in the string
    return strlen($text);
}
function my_ofset($text){
    preg_match('/^'D*(?='d)/', $text, $m);
    return isset($m[0]) ? strlen($m[0]) : false;
}

应该对此有效。最初的代码要求第一个数字之前有一个-,也许这就是问题所在?

我可以执行正则表达式,但必须进入已更改的状态记住我编码后它的作用。

这里有一个简单的PHP函数,你可以使用。。。

function findFirstNum($myString) {
    $slength = strlen($myString);
    for ($index = 0;  $index < $slength; $index++)
    {
        $char = substr($myString, $index, 1);
        if (is_numeric($char))
        {
            return $index;
        }
    }
    return 0;  //no numbers found
}

问题

查找字符串中第一个出现的数字

解决方案

以下是javascript 中的非正则表达式解决方案

var findFirstNum = function(str) {
    let i = 0;
    let result = "";
    let value;
    while (i<str.length) {
      if(!isNaN(parseInt(str[i]))) {
        if (str[i-1] === "-") {
          result = "-";
        }
        while (!isNaN(parseInt(str[i])) && i<str.length) {
          result = result + str[i];
          i++;
        }
        break;
      }
      i++;
    }
    return parseInt(result);  
};

示例输入

findFirstNum("words and -987 555");

输出

-987