PostgreSQL模式匹配数字的字符串列

问题描述

| 给定一个以字符串为单位的测量表(即\“ 4.6英寸,3mm \”,\“长度:4.66in \”等),我想检索行,该行的本质是数字的左或右因为数字匹配。 换句话说,如果我要搜索\“ 6 \”: 匹配:\“ 6 in \”,\“ 6in \”,\“ asdf 6 in \”,等等 不匹配:\“ 16 in \”,\“ 6.6 in \”,\“ with 66 in \”,等等 到目前为止,我有以下查询
select distinct length from items where length ~ \'[[:<:]]6[[:>:]]\';
但这并不是我想要的,这是结果:
     length      
---------------
 6.25 Inches
 4.6666 Inches
 6.5 Inches
 1.66 Inches
 6 Inches
 6.75 Inches
 6.71 Inches
 24.6 Inches
 3.6666 Inches
我正在使用Postgresql9。任何帮助将不胜感激。谢谢     

解决方法

怎么样 :
\'^[^0-9]*6[^0-9]*$\'
    ,据我了解,您希望字符串中的数字完全匹配。因此,数字(在您的情况下为6)不能用数字或十进制符号包围。因此,正则表达式应如下所示:
[^0-9\\.]6[^0-9\\.]
您可以将6更改为您要查找的任何数字。     ,
create table foo (length text);
insert into foo values (\'6 in\'),(\'asdf 6 in\'),(\'6in\'),(\'16 in\'),(\'6.6 in\'),(\'6.6\'),(\'with 66 in\');
select distinct length from foo where length ~ \'[^0-9 .][0-5.7-9 ]*6|6*[0-5.7-9 ]*[^0-9 .]\';
经过编辑,可以与\'6 \'和\'6.6 \'一起正常使用。     ,没有冒犯,但是将其存储为varchar并不是一个好主意。 应将其存储为两个单独的字段(数量/单位),或者(更好)存储为单个字段(具有预定义单位(例如,mm)的数量),并进行相应查询。