r - 如何删除一组特定字符之前的所有内容(例如,“? - ”)?
问题描述
我想删除“? - ”之前的所有内容,包括字符本身(问号、空格、连字符、空格)。我知道可以删除特定字符之前的所有内容。我不想只删除连字符 - 之前的所有内容,因为我还有其他带有连字符的语句。我试过这个,但它不适用于连字符。
例子:
gsub(".*-", "", "To what extent do you disagree or agree with the following statements? - Statistics make me cry.")
gsub(".*-", "", "To what extent do you disagree or agree with the following statements? - T-tests are easy to interpret.")
Output:
" Statistics make me cry."
"tests are easy to interpret."
我希望第二个语句显示为T-tests are easy to interpret
解决方案
这里sub
就足够了,而不是 global g
。更改模式以匹配?
(元字符 - 所以它被转义\\
),后跟零个或多个空格 ( \\s*
) -
,然后是零个或多个空格,替换为空白 ( ''
)
sub(".*\\?\\s*-\\s*", "", v1)
#[1] "Statistics make me cry." "T-tests are easy to interpret."
数据
v1 <- c("To what extent do you disagree or agree with the following statements? - Statistics make me cry.",
"To what extent do you disagree or agree with the following statements? - T-tests are easy to interpret."
)
推荐阅读
- spring - 无法将 osgi 服务 bean 公开为类而不是接口
- asp.net - 如何防止对aspx页面的CSRF攻击?
- python - Python中用户类的序列化
- c - 将字符串从指针复制到指针数组中的索引
- python - 当我添加 csrf 中间件时,Django 导致 403 禁止错误
- php - PHP在嵌套的foreach内部中断时
- cmd - Winrar 命令行在不使用通配符时不删除递归
- node.js - 如何在同一个 Heroku 应用上部署 Front & Back node.js?
- express - 有没有办法在sails中间件中添加额外的参数?
- shibboleth - 单个 sp 连接 shibboleth SSO 中的多个 Idp