gpt4 book ai didi

r - 提取字符串中的第一句话

转载 作者:行者123 更新时间:2023-12-01 09:14:13 25 4
gpt4 key购买 nike

我想用正则表达式从后面提取第一句话。我想要实现的规则(我知道这不是通用解决方案)是从字符串开始提取 ^最多(包括)前面是小写字母或数字的第一个句号/感叹号/问号 .

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."

到目前为止,我最好的猜测是尝试实现一个非贪婪的 string-before-match approach在这种情况下失败:
str_extract(x, '.+?(?=[a-z0-9][.?!] )')
[1] NA

任何提示非常感谢。

最佳答案

你把[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."

this regex demo .

详情
  • .*? - 除换行符以外的任何 0+ 个字符
  • [a-z0-9] - ASCII 小写字母或数字
  • [.?!] - 一个 . , ?!
  • (?= ) - 后面跟着一个文字空格。

  • 或者,您可以使用 sub :
    sub("([a-z0-9][?!.])\\s.*", "\\1", x)

    this regex demo .

    详情
  • ([a-z0-9][?!.]) - 第 1 组(引用替换模式中的 \1):一个 ASCII 小写字母或数字,然后是一个 ? , !.
  • \s - 一个空格
  • .* - 任何 0+ 个字符,尽可能多(直到字符串末尾)。
  • 关于r - 提取字符串中的第一句话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48884868/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com