用字符串提取第一句

geo*_*ory 3 regex r stringr

我想从正则表达式中提取下面的第一句话.我想要实现的规则(我知道它不是通用解决方案)是从字符串启动中提取^(包括)以小写字母或数字开头的第一个句点/感叹号/问号.

require(stringr)

x = "Bali bombings: U.S. President George W. Bush amongst many others has condemned the perpetrators of the Bali car bombing of October 11. The death toll has now risen to at least 187."
Run Code Online (Sandbox Code Playgroud)

到目前为止,我最好的猜测是在这种情况下尝试实现非贪婪的字符串匹配前方法失败:

str_extract(x, '.+?(?=[a-z0-9][.?!] )')
[1] NA
Run Code Online (Sandbox Code Playgroud)

任何提示非常感谢.

Wik*_*żew 5

你把它[a-z0-9][.?!]放到一个非消费的超前模式中,如果你打算使用它,你需要使它消耗str_extract:

> str_extract(x, '.*?[a-z0-9][.?!](?= )')
[1] "Bali bombings: U.S. President George W. Bush amongst many others has condemned the perpetrators of the Bali car bombing of October 11."
Run Code Online (Sandbox Code Playgroud)

看到这个正则表达式演示.

细节

  • .*? - 除了换行符之外的任何0+字符
  • [a-z0-9] - ASCII小写字母或数字
  • [.?!]- a .,?!
  • (?= ) - 接下来是文字空间.

或者,您可以使用sub:

sub("([a-z0-9][?!.])\\s.*", "\\1", x)
Run Code Online (Sandbox Code Playgroud)

看到这个正则表达式演示.

细节

  • ([a-z0-9][?!.])- 第1组(\1从替换模式引用):ASCII小写字母或数字,然后是a ?,!.
  • \s - 一个空白
  • .* - 任何0+字符,尽可能多(直到字符串结尾).