【问题标题】:splitting strings in oracle sql based on length基于长度分割oracle sql中的字符串
【发布时间】:2012-08-02 05:24:02
【问题描述】:

我想在 Oracle 中根据长度分割我的字符串,并用空格作为分隔符。

例如,

MY_STRING="welcome to programming world"

我的输出应该是

STRING1="welcome to "
STRING2="programming "

字符串的长度不得超过 13 个字符。 26位之后的单词可以忽略。

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    您没有提及您使用的是哪个版本的 Oracle。如果您使用的是 10g 或以上,您可以使用regular expressions 来获取您需要的内容:

    with spaces as (
     select regexp_instr('welcome to programming world' || ' '
                        , '[[:space:]]', 1, level) as s
       from dual
    connect by level <= regexp_count('welcome to programming world' || ' '
                                    , '[[:space:]]')
            )
    , actual as (
     select max(case when s <= 13 then s else 0 end) as a
          , max(case when s <= 26 then s else 0 end) as b
       from spaces
            )
    select substr('welcome to programming world',1,a)
         , substr('welcome to programming world',a, b - a)
      from actual
    

    这会找到所有空格的位置索引,然后找到最接近但小于 14 的那个。最后使用简单的substr 来拆分您的字符串。字符串将有一个尾随空格,因此您可能想要trim this。

    你必须用空格连接你的字符串以确保有一个尾随空格,这样如果你的字符串短于 26 个字符,最后一个单词就不会被删除。

    假设您使用的是早期版本,您可以将 instrlength 一起破解,但它根本不会很漂亮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 2019-02-18
      • 2012-06-29
      • 2021-09-23
      • 1970-01-01
      • 2020-12-19
      相关资源
      最近更新 更多