【问题标题】:Oracle regexp_replace - Adding space to separate sentencesOracle regexp_replace - 为单独的句子添加空格
【发布时间】:2017-01-14 03:57:48
【问题描述】:

我正在 Oracle 中修复一些文本。问题是我的数据中的句子有句子没有用空格分隔的单词。例如:

  1. 句子之间没有空格

  2. 句子带问号?第二句

我已经在 regex101 中测试了以下替换语句,它似乎可以正常工作,但我无法确定为什么它在 Oracle 中不起作用:

regexp_replace(review_text, '([^\s\.])([\.!\?]+)([^\s\.\d])', '\1\2 \3')

这应该允许我查找句子分隔句点/感叹号/问号(单个或分组)并在句子之间添加必要的空格。我意识到还有其他方法可以分隔句子,但我上面的内容应该涵盖了大部分用例。第三个捕获组中的 \d 是为了确保我不会不小心将诸如“4.5”之类的数值更改为“4.5”。

测试组前:

Sentence without space.Between sentences
Sentence with space. Between sentences
Sentence with multiple periods...Between sentences
False positive sentence with 4.5 Liters
Sentence with!Exclamation point
Sentence with!Question mark

修改后应该是这样的:

Sentence without space. Between sentences
Sentence with space. Between sentences
Sentence with multiple periods... Between sentences
False positive sentence with 4.5 Liters
Sentence with! Exclamation point
Sentence with! Question mark

Regex101 链接:https://regex101.com/r/dC9zT8/1

虽然所有更改都按 regex101 的预期工作,但我在 Oracle 中遇到的问题是我的第三个和第四个测试用例没有按预期工作。 Oracle 没有在多个句点(省略号)组之后添加空格,而 regexp_replace 正在为“4.5”添加空格。我不确定为什么会出现这种情况,但也许我缺少关于 Oracle regexp_replace 的一些特殊性。

任何和所有的见解都是值得赞赏的。谢谢!

【问题讨论】:

  • 我的猜测是在 regex101 而不是 Oracle 中打开的是全局匹配(g 标志)。
  • 全局发生是我没有想到的,但即使在 Oracle 中使用设置发生 = 0,我仍然遇到同样的问题。

标签: regex oracle oracle12c


【解决方案1】:

这可能会让您入门。这将检查.?!在任何组合中,后跟零个或多个空格和一个大写字母,它将用一个空格替换“零个或多个空格”。这不会分隔十进制数;但它会遗漏以非大写字母开头的句子。您可以开始添加条件 - 如果您遇到困难,请回信,我们会尽力提供帮助。参考其他正则表达式方言可能会有所帮助,但这可能不是获得答案的最快方法。

with
     inputs ( str ) as (
       select 'Sentence without space.Between sentences'           from dual union all
       select 'Sentence with space. Between sentences'             from dual union all
       select 'Sentence with multiple periods...Between sentences' from dual union all
       select 'False positive sentence with 4.5 Liters'            from dual union all
       select 'Sentence with!Exclamation point'                    from dual union all
       select 'Sentence with!Question mark'                        from dual
     )
select regexp_replace(str, '([.!?]+)\s*([A-Z])', '\1 \2') as new_str
from   inputs;

NEW_STR
-------------------------------------------------------
Sentence without space. Between sentences
Sentence with space. Between sentences
Sentence with multiple periods... Between sentences
False positive sentence with 4.5 Liters
Sentence with! Exclamation point
Sentence with! Question mark

6 rows selected.

【讨论】:

  • 感谢 mathguy - 你写的东西在逻辑上是合理的。我将应用您提供的内容(尽管我也会使用小写的 a-z)并检查是否缺少任何内容。
猜你喜欢
  • 2019-04-05
  • 2018-08-14
  • 1970-01-01
  • 2015-08-09
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
相关资源
最近更新 更多