简体   繁体   English

如何从字符串中提取数字部分

[英]how to extract the digit part from the string

I have a column that has a string in it as follow 我有一个列中有一个字符串,如下所示

Data
black83736
white87
white893
pink82928
pink1
black27
...
...

I want to just get the digits out of that column. 我想从该列中获取数字。

Edit 编辑

I would prefer mysql solution 我更喜欢mysql解决方案

Try this mysql Solution : (updated) 试试这个mysql解决方案:(更新)

SELECT replace(reverse(FORMAT(reverse(COLUMN_NAME), 0)), ',', '') as number from TABLE_NAME;

this is for your particular case, where you want the numbers in the end. 这是针对您的特定情况,您最终需要数字。

so first we 首先我们

Reverse , so numbers come to beginning Reverse ,所以数字开始

format , so alphabets are removed, format is used for formatting a number with specified decimal places, here we specify it to 0. format ,所以删除字母,格式用于格式化具有指定小数位的数字,这里我们将其指定为0。

reverse again -> to obtain the original number 再次reverse - >获取原始数字

replace ',' to '' -> to remove the effect of formatting of second step. replace ',' replace为'' - >以删除第二步格式化的效果。

** **

(UPDATE) (UPDATE)

** the above solution doesnt work for numbers ending in 0's (thanks to karolis for telling) **上述解决方案不适用于以0结尾的数字(感谢karolis告诉)

so for that 所以为此

SELECT replace(replace(reverse(FORMAT(reverse(concat(numbers, '9099')), 0)), ',', ''), '9099', '') as number from test1;

Here we are appending '9099' to the end of the number, and then removing 9099 in the end. 在这里,我们将“9099”附加到数字的末尾,然后最后删除9099。

9099 ? 9099? just a number which would be highly in-probable to occur in your columns 只是一个很可能在您的列中出现的数字

$result = preg_replace('~[^0-9]*~', '', $string);

Yes, it's very inelegant, but currently the only reliable MySQL only solution that I know: 是的,它非常不优雅,但目前是我所知道的唯一可靠的MySQL解决方案:

select replace(column_name,
    replace(replace(replace(replace(replace(
    replace(replace(replace(replace(replace(
    column_name, 
    0, ''), 1, ''), 2, ''), 3, ''), 4, ''), 
    5, ''), 6, ''), 7, ''), 8, ''), 9, ''), '')
filter_var('stri99ng', FILTER_SANITIZE_NUMBER_INT);

I would prefer mysql solution 我更喜欢mysql解决方案

Well, you shouldn't unless you have powerful processor or this query does not return many results. 好吧,你不应该除非你有强大的处理器或这个查询不会返回很多结果。 MySQL isn't generally good for any string manipulation operations. MySQL通常不适合任何字符串操作操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM