【问题标题】:How to replace the new line and line feed in a specific manner如何以特定的方式替换新的换行符和换行符
【发布时间】:2018-11-29 07:25:14
【问题描述】:

我在 oracle 中名为“DATA”的列中有以下数据。我试图在每行之后删除新的空行。

  • 输入

    This is a text from line 1.
    
    This is text from line 2.
    
    This is a text from line 3.The line 3 ends here .
    
    This is a text from line 4.The line ends here .
    
  • 输出

    This is a text from line 1.
    This is text from line 2.
    This is a text from line 3.The line 3 ends here .
    This is a text from line 4.The line ends here .
    

我尝试过使用

查询:

Select regexp_replace(regexp_replace(data,chr(13),null),chr(10),null) from main_data;

当我执行下面的查询时,输出就像一个段落。

这是第 1 行的文本。这是第 2 行的文本。这是第 3 行的文本。第 3 行到此结束。这是第 4 行的文本。行到此结束。

任何人都可以说如何实现这一目标吗?

【问题讨论】:

标签: regex oracle oracle11g regexp-replace


【解决方案1】:

您可以使用'(' || chr(13) || chr(10) || '?|' || chr(10) || '){2,}' 正则表达式:

select regexp_replace(
    'This is a text from line 1.' || chr(13) || chr(10) || chr(13) || chr(10) || 'This is text from line 2.' || chr(10)  || chr(10) || 'This is a text from line 3.The line 3 ends here .'  || chr(10) || chr(10) || 'This is a text from line 4.The line ends here .',
    '(' || chr(13) || chr(10) || '?|' || chr(10) || '){2,}',
    '\1') as Result from dual

该模式匹配 2 次或更多 ({2,}) 连续重复的 CR 符号,后跟可选的(1 或零,?)LF 符号或(|)LF 符号。

匹配被替换为最后一次匹配的 CRLF、CR 或 LF,因为 \1 是使用捕获组 #1 捕获的值的占位符(模式中的第一个 (...) 构造)。

online demo 的输出:

【讨论】:

  • 完美。这就像一个魔术。在您提供的查询中 ('\1') 我们为什么要使用它? .
  • @SanthoshPogaku 正则表达式匹配2个或多个连续换行符,如果我们替换为'',我们将删除它们并将所有行合并为1。我们需要用换行符替换,并且我展示了我们如何在替换中重用捕获的值(参见 \1 是使用捕获组 #1 捕获的值的占位符(模式中的第一个 (...) 构造) )。如果愿意,您可以将其硬编码为 chr(10) 或 char(13) || chr(10)。
  • 顺便说一句,您可能想使用'(' || chr(13) || chr(10) || '?|' || chr(10) || '){2,}' 来匹配所有常见的换行符结尾:CRLF、LF 或 CR。
  • 感谢您的解决方案和解释,该解决方案非常适合我的问题。泰。
【解决方案2】:

如果字段为空白或NULL,请使用以下内容。

SELECT DATA
FROM main_data
WHERE DATA IS NOT NULL OR DATA != ''

【讨论】:

  • [DATA != ''] 是多余的。这绝不是真的,因为 '' 在 Oracle 中被视为 null。
  • OP 似乎在谈论一个单行值,它是一个嵌入空行的字符串;不是多行,其中一些为空。
【解决方案3】:

如何将连续出现的行尾标记替换为一个。

DECLARE

  DATA VARCHAR2(2000);
BEGIN
  DATA := 'This is a text from line 1.' || CHR(13) || CHR(13) ||
          'This is text from line 2.' || CHR(13) || CHR(13) ||
          'This is a text from line 3.The line 3 ends here .' || CHR(13) ||CHR(13) ||
          'This is a text from line 4.The line ends here .';

  dbms_output.put_line(regexp_replace(DATA, chr(13) || CHR(13), CHR(13)));

END;

这会给你

This is a text from line 1.
This is text from line 2.
This is a text from line 3.The line 3 ends here .
This is a text from line 4.The line ends here .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2022-01-05
    • 2012-03-07
    相关资源
    最近更新 更多