regex - 如何简化 postgres regexp_replace

标签 regex postgresql

有没有一种方法可以仅使用一个 regexp_replace 来简化此查询?

select regexp_replace(regexp_replace('BL 081', '([^0-9.])', '', 'g'), '(^0+)', '', 'g')

the result should be 81

我正在尝试从结果中删除所有非数字字符和前导 0

最佳答案

您可以通过捕获所需的数字(不包括任何前导零)并删除其他所有内容来做到这一点:

select regexp_replace('BL 0081', '.*?([1-9][0-9]*)$', '\1')

输出

81

请注意,您不需要 g 标志,因为您只需要替换一个。

Demo on dbfiddle

关于regex - 如何简化 postgres regexp_replace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524883/

相关文章:

正则表达式 懒惰与贪婪混淆

java - 如何更正正则表达式以在不区分大小写的情况下找到精确的单词匹配?

regex - 时髦的 : RegEx for matching Alphanumeric and underscore and dashes

hibernate - 组织.hibernate.exception.SQLGrammarException : could not insert:

python:在逗号和点之后拆分字符串

regex - 从日志文件中提取特定的 XML

sql - 在 Postgres 中使用 OR 条件时会跳过查询计划中的索引

postgresql - 如何从 PostgreSQL 中的 RelOptInfo 获取表名或 ID?

postgresql - PostgreSQL 可以推荐最佳字段类型吗?

java - PostgreSQL JDBC SSL