【问题标题】:extract string using same pattern in a text using R使用 R 在文本中使用相同模式提取字符串
【发布时间】:2017-07-10 13:30:28
【问题描述】:

我正在尝试用 R 处理文本,这是我的问题。

来自此源文本

#Pray4Manchester# I hope that #ArianaGrande# will be better soon.

我想使用模式#.+# 提取Pray4ManchesterArianaGrande,但是当我运行时

str_extract_all(text,pattern="#.+#")

我明白了

#Pray4Manchester# I hope that #ArianaGrande#

如何解决这个问题?谢谢。

【问题讨论】:

  • 它不起作用,因为字符# 也匹配模式.+,这(我猜)导致str_extract 贪婪地寻找最广泛的匹配。您将需要本身不包含 # 的模式,例如 akrun 建议的模式。
  • 你需要使用非贪婪修饰符str_extract_all(text,pattern="#.+?#")

标签: r string text


【解决方案1】:

我们可以的

str_extract_all(text, "(?<=#)\\w*(?=#)")[[1]]
#[1] "Pray4Manchester" "ArianaGrande"   

数据

text <- "#Pray4Manchester# I hope that #ArianaGrande# will be better soon."

【讨论】:

    【解决方案2】:

    您可以使用正则表达式来查找与两个不包含空格字符的哈希之间的文本匹配的结果。

    类似这样的:([#]{1}[^\s]+[#]{1})

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-18
      • 2012-07-07
      • 1970-01-01
      • 2020-11-02
      • 2022-12-18
      • 2019-09-28
      • 2021-11-28
      • 1970-01-01
      相关资源
      最近更新 更多