让我首先提到,这是一个经过充分讨论的问题,我经历了几个线程,包括这两个线程--它们最接近于Regex to match a string not followed by some string和A regex to match a substring that isn't followed by a certain other substring,但它们并没有解决我的问题。
我的字符串包含了几种不同格式的-mentioned,例如6×200毫升平均6包200毫升。我只想提取这个例子中类似于6的数量。
示例
到目前为止,我一直在努力,但没有成功。
(X\s*\d+|\d+\s*X)(?!\s*ml)它也与第3和第4种情况相匹配,而这两种情况不应该匹配。我也可以用乘法符号6,而不是6,而不是仅仅6,我可以替换它。
发布于 2018-01-29 07:29:20
你没有提到你在这个问题上使用的数据库。
SQL标准不包括正则表达式,因此每个数据库都有自己的regexp引擎实现,每个正则表达式都是不同的,并且不支持正则表达式的许多特性,比如查找器。如果不知道您正在使用的确切数据库,就很难帮助您。
下面是两个简单的示例,说明如何在Oracle和PostgreSQL数据库中使用
但是,除了/PostgreSQL之外,其他数据库上也不能使用这种方法。
对Oracle的查询:
在线演示:http://sqlfiddle.com/#!4/599c41/5
select t.*,
regexp_substr( regexp_replace( "text", '\d+\s*ml', '///' ), '\d+' ) as x
from table1 t;
| text | X |
|-------------------|--------|
| blah 6 X 200ml | 6 |
| blah 200 mlX 6 | 6 |
| blah x 5000 ml | (null) |
| blah x 500000ml | (null) |
| blah 5mlX10 | 10 |
| blah 500 mlX 10 | 10 |如果要用0或1替换NULL,可以用这种方式使用CASE表达式:
select t.*,
CASE WHEN regexp_substr( regexp_replace( "text", '\d+\s*ml', '///' ), '\d+' )
IS NULL THEN '1' /* or 0 */
ELSE regexp_substr( regexp_replace( "text", '\d+\s*ml', '///' ), '\d+' )
END as x
from table1 t;
| text | X |
|-------------------|----|
| blah 6 X 200ml | 6 |
| blah 200 mlX 6 | 6 |
| blah x 5000 ml | 1 |
| blah x 500000ml | 1 |
| blah 5mlX10 | 10 |
| blah 500 mlX 10 | 10 |对PostgreSQL:的查询
select t.*,
substring( regexp_replace( "text", '\d+\s*ml', '///') from '\d+' ) as x
from table1 t;
| text | x |
|-------------------|--------|
| blah 6 X 200ml | 6 |
| blah 200 mlX 6 | 6 |
| blah x 5000 ml | (null) |
| blah x 500000ml | (null) |
| blah 5mlX10 | 10 |
| blah 500 mlX 10 | 10 |在线演示:http://sqlfiddle.com/#!17/b003b/1
https://stackoverflow.com/questions/48493672
复制相似问题