Extract a single integer from a string

后端 未结 21 2500
一个人的身影
一个人的身影 2020-11-21 23:33

I want to extract the digits from a string that contains numbers and letters like:

"In My Cart : 11 items"

I want to extract the nu

相关标签:
21条回答
  • 2020-11-22 00:01

    This script creates a file at first , write numbers to a line and changes to a next line if gets a character other than number. At last, again it sorts out the numbers to a list.

    string1 = "hello my name 12 is after 198765436281094and14 and 124de"
    f= open("created_file.txt","w+")
    for a in string1:
        if a in ['1','2','3','4','5','6','7','8','9','0']:
            f.write(a)
        else:
            f.write("\n" +a+ "\n")
    f.close()
    
    
    #desired_numbers=[x for x in open("created_file.txt")]
    
    #print(desired_numbers)
    
    k=open("created_file.txt","r")
    desired_numbers=[]
    for x in k:
        l=x.rstrip()
        print(len(l))
        if len(l)==15:
            desired_numbers.append(l)
    
    
    #desired_numbers=[x for x in k if len(x)==16]
    print(desired_numbers)
    
    0 讨论(0)
  • 2020-11-22 00:02

    This functions will also handle the floating numbers

    $str = "Doughnuts, 4; doughnuts holes, 0.08; glue, 3.4";
    $str = preg_replace('/[^0-9\.]/','-', $str);
    $str = preg_replace('/(\-+)(\.\.+)/','-', $str);
    $str = trim($str, '-');
    $arr = explode('-', $str);
    
    0 讨论(0)
  • 2020-11-22 00:04

    other way(unicode string even):

    $res = array();
    $str = 'test 1234 555 2.7 string ..... 2.2 3.3';
    $str = preg_replace("/[^0-9\.]/", " ", $str);
    $str = trim(preg_replace('/\s+/u', ' ', $str));
    $arr = explode(' ', $str);
    for ($i = 0; $i < count($arr); $i++) {
        if (is_numeric($arr[$i])) {
            $res[] = $arr[$i];
        }
    }
    print_r($res); //Array ( [0] => 1234 [1] => 555 [2] => 2.7 [3] => 2.2 [4] => 3.3 ) 
    
    0 讨论(0)
  • 2020-11-22 00:05

    If you just want to filter everything other than the numbers out, the easiest is to use filter_var:

    $str = 'In My Cart : 11 items';
    $int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);
    
    0 讨论(0)
  • 2020-11-22 00:07
    $value = '25%';
    

    Or

    $value = '25.025$';
    

    Or

    $value = 'I am numeric 25';
    $onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
    

    This will return only the numeric value

    0 讨论(0)
  • 2020-11-22 00:08

    Using preg_replace

    $str = 'In My Cart : 11 12 items';
    $str = preg_replace('/\D/', '', $str);
    echo $str;
    
    0 讨论(0)
提交回复
热议问题