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

▼魔方 西西 提交于 2019-12-09 02:57:48

问题


Can someone help me with algorithm for finding the position of the first occurrence of any number in a string?

The code I found on the web does not work:

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

回答1:


function my_ofset($text){
    preg_match('/^\D*(?=\d)/', $text, $m);
    return isset($m[0]) ? strlen($m[0]) : false;
}

should work for this. The original code required a - to come before the first number, perhaps that was the problem?




回答2:


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



回答3:


The built-in PHP function strcspn() will do the same as the function in Stanislav Shabalin's answer when used like so:

strcspn( $str , '0123456789' )

Examples:

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




回答4:


I can do regular expressions but I have to go into an altered state to remember what it does after I've coded it.

Here is a simple PHP function you can use...

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
}



回答5:


Problem

Find the first occurring number in a string

Solution

Here is a non regex solution in 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);  
};

Example Input

findFirstNum("words and -987 555");

Output

-987


来源:https://stackoverflow.com/questions/7495603/find-the-position-of-the-first-occurrence-of-any-number-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!