如何以特定方式替换新的换行和换行

时间:2018-06-20 08:17:40

标签: regex oracle oracle11g regexp-replace

我在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行的文本。在这里结束行。

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

3 个答案:

答案 0 :(得分:3)

您可以使用'(' || 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的输出:

enter image description here

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

您如何用一个来代替连续出现的行尾标记呢?

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 .