【问题标题】:Oracle - use regular expression to format capturing groupsOracle - 使用正则表达式格式化捕获组
【发布时间】:2021-03-08 16:16:11
【问题描述】:

我希望使用 REGEXP_REPLACE(或等效函数)将我的字符串格式化为固定长度输出。

例如。我的输入始终是 3 组随机字符串,以逗号分隔。 我希望每个捕获组的输出具有 10 个字符的固定长度(用“_”填充)。

输入:

abc,def,ghi
085,10,1234567
long words,tom,jerry

期望的输出:

_______abc_______def_______ghi
_______085________10___1234567
long words_______tom_____jerry

所以代码应该是这样的:

select regexp_replace( input, '([^,]+),([^,]+),([^,]+)',
                       LPAD('\1', '_', 10) || LPAD('\2', '_', 10) || LPAD('\3', '_', 10) ) 
from <table>

这显然没有按预期进行。

有什么想法吗?

【问题讨论】:

  • 反向引用仅在字符串模式中被解析。您不能将它们用作其他函数的参数,然后将它们视为文字字符串。

标签: regex oracle plsql


【解决方案1】:

通过多个替换和连接,您可以这样做:

select
    lpad(regexp_replace('085,10,1234567', ',.*$', ''), 10, '_') || -- remove the first period and everything after it
    lpad(regexp_replace('085,10,1234567', '^[^,]+,|,[^,]+$', ''), 10, '_') || -- remove the first period, everything before it, and the last period plus everything after it
    lpad(regexp_replace('085,10,1234567', '^.*,', ''), 10, '_') as whatever -- remove the last period and everything before it
from
    dual

只需将'085,10,1234567' 替换为您的input

这个例子产生:

_______085________10___1234567

【讨论】:

  • 太棒了。我没想到要调用它 3 次!
  • @Samuel 很高兴你喜欢它,请随时将我的回答标记为已接受 :)
猜你喜欢
  • 2016-03-21
  • 2019-11-14
  • 2018-03-11
  • 1970-01-01
  • 2012-03-31
  • 2018-07-21
  • 1970-01-01
相关资源
最近更新 更多