Use SQL REGEXP to ignore number and get only String and '/'

流过昼夜 提交于 2019-12-22 18:00:02

问题


I have a MySQL table with a column of type varchar(255) which holds the data in the following formats:

400 mg
50/12,5 mg/ml
20 mikrog
500 mg/400 IU
60 mikrog/15 mikrog

I need to ignore the number and only extract the string(s), in some cases, including /, so that the data from above looks like this:

mg
mg/ml
mikrog
mg/IU
mikrog/mikrog

I tried using REGEXP like this:

SELECT DISTINCT REGEXP_SUBSTR(column, '[a-z]') FROM db.table;

But, that just gives me a bunch of letters, like this

m
I
U
a
g
k

Is there any way to use REGEXP to extract String of any length, as in my case, the String that needs extracting is of varying length, for example, in case of mg, it's 2, in case of mikrog, it's 6. Also, in some cases, I need to include the character /.


回答1:


You may remove the numbers to get what you need:

REGEXP_REPLACE(column, ' *[0-9]+([.,][0-9]+)?(/[0-9]+([.,][0-9]+)?)? *', '')

See the regex demo.

Details

  • * - 0+ spaces
  • [0-9]+ - 1+ digits
  • ([.,][0-9]+)? - an optional sequence of a comma or period followed with 1+ digits
  • (/[0-9]+([.,][0-9]+)?)? - an optional sequence of a / and then 1+ digits followed optionally with . or , and 1+ digits
  • * - 0+ spaces



回答2:


If you want to use regexp

Try to use [a-z]* to get only all letters, or [a-z]*\/[a-z]* to get even the slash.

Take a look here and test some examples




回答3:


The easiest way is using instr() and substring()

select substring(col, instr(col, ' '))
from your_table

SQLFiddle demo



来源:https://stackoverflow.com/questions/57250535/use-sql-regexp-to-ignore-number-and-get-only-string-and

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