我有一个数据集,其中有一列包含字符串,
例子
“管理 250,000 美元的预算,利用 Excel 监控运营支出并将其与之前的预算进行比较,从而为公司节省了 10% 的预算”
我想标记所有带有美元符号后跟数字的字符串。
我正在尝试这样编码
grep("$[^0-9]", cand_emp$description, ignore.case = TRUE, perl = FALSE, value = FALSE,
fixed = FALSE, useBytes = FALSE, invert = FALSE)
看来,这不是正确的编码方式。
非常感谢任何帮助
谢谢! 部分
最佳答案
因为美元符号是一个特殊字符,你必须通过在反斜杠前加一个反斜杠来转义它:
\$
您可以查看 documentation
The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any metacharacter with special meaning may be quoted by preceding it with a backslash. The metacharacters in extended regular expressions are . \ | ( ) [ { ^ $ * + ?, but note that whether these have a special meaning depends on the context.
更新:如 Gregor 在他的评论中指出,你必须转义 R 中的反斜杠,所以你必须使用:
\\$
你可以:
grep("\\$[^0-9]", cand_emp$description, ignore.case = TRUE, perl = FALSE, value = FALSE,
fixed = FALSE, useBytes = FALSE, invert = FALSE)
另一方面,如果您不喜欢两个反斜杠,您可以使用 [``]
来利用字符类:
grep("[$][^0-9]", cand_emp$description, ignore.case = TRUE, perl = FALSE, value = FALSE,
fixed = FALSE, useBytes = FALSE, invert = FALSE)
更新:我注意到您用我想标记所有带有美元符号后跟数字的字符串更新了您的问题。为此,您必须从示例中删除 ^
,使用:
[$][0-9]+
关于regex - 如何在 R 中的字符串中搜索美元符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29781277/