静谧
发布于

parse 字段(可能使用 regex)时

有一个 MySQL (MySQL v8) 表,其中一列包含长字符串信息,但当选择它时,只需要检索长字符串的特定部分。

需要将紧接在 “ - ” 部分之前和该部分之后的值作为响应的一部分(除非字符串的开头,在这种情况下没有

)

create table codes (
    id integer primary key
    desc text not null
);

insert into codes values (1, '423.9 - This is the first item<Br>511.9 - This is the second item<Br>486 - This is the third item (486.0 actually)<Br>42.a.7.31 - <Br>785.0 - 785.? unsure if decimal is correct')

insert into codes values (2, '428.0M - CHF NOS')

insert into codes values (3, 'E.423.9 - Just testing!<Br>511.9 - Another test 12345')

需要紧接在 ' - ' 部分之前的描述部分,例如在“select ...from codes“我会有这个:

423.9, 511.9, 486, 42.a.7.31, 785.0
428.0M
E.423.9, 511.9
浏览 (5)
点赞
收藏
1条评论
Klustron小助手
理想情况下,在将数据导入数据库之前,您应该使用 MySQL 之外的某种脚本语言(例如 Python、Perl)执行此清理操作。话虽如此,在 MySQL 8+ 上,我们可以尝试使用 for 正则表达式选项来提取所需的术语:REGEXP_REPLACE() SELECT id, `desc`, REGEXP_REPLACE(REGEXP_REPLACE(`desc`, &#39;([^ ]+).*?(&lt;Br&gt;|$)&#39;, &#39;$1, &#39;), &#39;, $&#39;, &#39;&#39;) AS output FROM codes; 此处使用的正则表达式模式匹配: ([^ ]+)match AND capture 在第一个非空格术语中$1 .*?match 直到到达最近的 (&lt;Br&gt;|$) &lt;Br&gt;tag OR 字符串的结尾 然后,我们替换 with ,后跟逗号和空格,以构建所需的 CSV 字符串。请注意,外部调用 to 是为了去除最后一个悬空逗号。$1REGEXP_REPLACE
点赞
评论