2017-05-11 49 views
-1

我试图找到一个正则表达式,它将一段文本拆分为./?/!之后的一个空格,后面跟着一个大写字母。按句点分割句子后跟一个大写字母

"Hello there, my friend. In other words, i.e. what's up, man." 

应该拆分:

Hello there, my friend| In other words, i.e. what's up, man| 

我可以得到它拆就./?/!,但我没有运气得到的空间和大写字母的标准。

我想出什么样的主意:

.split("/. \s[A-Z]/") 
+0

向我们展示你的正则表达式到目前为止使用。 –

+0

到目前为止你写了哪些正则表达式? – gaganshera

+0

请注意,根据你的要求,最后的'.'不应该分开。 –

回答

3

拆分一段文字为句子基础上,这是一个标准的./?/!接着是一个大写字母后面的空格。

您可以使用基于一个超前正则表达式:

s = "Hello there, my friend. In other words, i.e. what's up, man." 
puts s.split(/[!?.](?=\s+\p{Lu})/) 

Ruby demo。如果您还需要在字符串末尾使用标点符号进行拆分,请使用/[!?.](?=(?:\s+\p{Lu})|\s*\z)/

详细

  • [!?.] - 匹配的!?.这是...
  • (?=\s+\p{Lu}) - (正前瞻),随后与1+空格,接着用1个大写字母立即当前位置的权利。

查看Rubular demo

注意:如果您需要将常规英文文本拆分为句子,则应考虑使用现有的NLP解决方案/库。参见:

后者是基于正则表达式,并且可以容易地与多个正则表达式延长。

2

除了Wiktor的答案你还可以使用lookarounds找零宽度和分裂。

正则表达式:(?<=[.?!]\s)(?=[A-Z])发现零宽度由任一[.?!]和空间之前和之后的大写字母。

s = "Hello there, my friend. In other words, i.e. what's up, man." 
puts s.split(/(?<=[.?!]\s)(?=[A-Z])/) 

输出

Hello there, my friend. 
In other words, i.e. what's up, man. 

Ruby Demo


更新:基于Cary Swoveland's comment

如果OP想打破串入句子我建议(?<=[.?!])\s+(?=[A-Z]),因为它句子之间消除空间,并能使这种空间的数量大于一

+2

我不会在这里使用lookbehind,因为它的宽度是固定的,并且很难控制空白。但是,OP示例和要求不能100%匹配,目前无法提供最佳答案。 –

+0

@WiktorStribiżew:同意。 – Rahul

+0

如果OP想要将字符串分解成句子,我会建议'(?<= [。?!])\ s +(?= [AZ])',因为它删除句子之间的空格,并允许这些空格的数量大于一个。 –

相关问题