【问题标题】:How to select the first number in a string如何选择字符串中的第一个数字
【发布时间】:2020-11-06 05:16:23
【问题描述】:

基本上,我有一个很大的地址列表,有时可以以 FLAT "number"、"rest of address" 或 APARTMENT "number"、"rest of address" 或有时甚至是 "number"A、"rest of address" 开头或 FLAT "number"A.

如何选择第一个数字,如果数字有一个字符,那么也包括那个?

例子:

  • 如果地址是FLAT 3, thanos house, nw1 6fs那么我需要选择3
  • 如果地址是FLAT 3B, thanos house, nw1 6fs那么我需要选择3B
  • 如果地址是324, thanos house, nw1 6fs那么我需要选择324
  • 如果地址是APARTMENT 324, thanos house, nw1 6fs那么我需要选择324

【问题讨论】:

  • @a_horse_with_no_name 答案对我不起作用,回答者告诉我创建新问题

标签: sql regex postgresql


【解决方案1】:

这个substring() 表达式可以满足您的要求:

substring(string, '\m\d+\D?*\M')

正则表达式只返回第一个匹配项,如果没有,则返回NULL

\m ... beginning of a word
\d+ ... 一位或多位数字
\D? ... 零或一位非数字
\M ... @ 987654323@

演示:

SELECT string, substring(string, '\d+\D?\d*\M')
FROM  (
   VALUES
  ('FLAT 3, thanos house, nw1 6fs')
, ('FLAT 3B, thanos house, nw1 6fs')
, ('324, thanos house, nw1 6fs')
, ('APARTMENT 324, thanos house, nw1 6fs')
   ) tbl(string);

db小提琴here

【讨论】:

  • 完美!第一次看到 from (values tbl()) 也被使用了,所以也非常感谢!
  • @Luffydude: The manual on VALUES.
  • @ErwinBrandstetter 完美解决方案!学到了一些新东西:-)
猜你喜欢
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 2010-10-01
  • 2021-05-26
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
相关资源
最近更新 更多