【问题标题】:How to match a string with exactly one digit in R Studio? [closed]如何在 R Studio 中将字符串与恰好一位数字匹配? [关闭]
【发布时间】:2020-11-03 17:25:43
【问题描述】:

我正在尝试在 R Studio 中匹配一个恰好为一位数字的字符串 我已经有这个代码了:

grep("[:0-9:]+\d{0,1}]" , text_strings, value = TRUE)

但是输出还是错误的

【问题讨论】:

  • 一些预期输入和输出的例子在这里会有很大帮助!
  • 我会把它留给你翻译,但是:字符串的开头,0 个或多个非数字,一个数字,零个或多个非数字,字符串的结尾。找出正则表达式中每个模式的模式还不错。
  • "',' 是一个分隔符,所以请提取这些数字 125,789,1450 以及这些 564,90456", "我们愿意为您提供每月 7890 美元以完成此任务。 .. 我们在开玩笑”、“你将学习 3 件事,第一个不是提取,2 和 3 只是数字。”、“玩我们强大的测试,你将支持科学、进步,human wellness and you 所以这是文本,我需要过滤只有一位数字的行(例如倒数第二句中的 2 和 3)
  • 感谢您的帮助!实际上我试图在每个句子中提取一个数字,例如“我们愿意为您提供每月 7890 美元的费用来完成这项任务……我们在开玩笑”,“您将学习 3 件事,第一个不是提取,2 和 3 只是数字。 ”,“玩得开心我们的强大测试,你将支持科学、进步、人类健康和你所以这是文本,我需要用一个数字过滤行,所以这里的输出必须是 3、2 和3(表示 1 位)没有类似 125,789,1450 的东西,BC 有不止一位

标签: r digits


【解决方案1】:

由于grep()grepl() 不使用扩展正则表达式,我会尝试使用 stringr 包,如下所示:

text_strings = c("','is a separator, so please extract these numbers 125,789,1450 and also these 564,90456",
                 "We like to to offer you 7890$ per month in order to complete this task... we are joking",
                 "You are going to learn 3 things, the first one is not to extract, and 2 and 3 are simply digits.",
                 "Have fun with our mighty test, you are going to support science, progress, mankind wellness and you")
stringr::str_extract_all(text_strings, '(?<!\\d)\\d(?!\\d)')

输出:

[[1]]
character(0)

[[2]]
character(0)

[[3]]
[1] "3" "2" "3"

[[4]]
character(0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2020-05-02
    • 2019-04-08
    • 1970-01-01
    相关资源
    最近更新 更多