替换下划线“

编程入门 行业动态 更新时间:2024-10-28 08:21:31
本文介绍了替换下划线“_"带有反斜杠下划线“\_";在 R 字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

问:如何将 R 字符串中的下划线_"替换为反斜杠下划线_"?我更喜欢使用 stringr 包.

Q: How can I replace underscores "_" with backslash-underscores "_" in an R string? I'd prefer to use the stringr package.

另外,谁能解释为什么下面的第 5 行没有得到想要的结果?我几乎可以肯定这会奏效.

Also, can anyone explain why line 5 below fails to get the desired result? I was almost certain that would work.

library(stringr) s <- "foo_bar_baz" str_replace_all(s, "_", 5) # [1] "foo5bar5baz" str_replace_all(s, "_", "\_") # Error: '\_' is an unrecognized escape in character string starting ""\_" str_replace_all(s, "_", "\\_") # [1] "foo_bar_baz" str_replace_all(s, "_", "\\\_") # Error: '\_' is an unrecognized escape in character string starting ""\\\_" str_replace_all(s, "_", "\\\\_") # [1] "foo\\_bar\\_baz"

上下文:我正在使用 xtable 制作 LaTeX 表,并且需要清理我的列名,因为它们都有下划线并破坏 LaTeX.

Context: I'm making a LaTeX table using xtable and need to sanitize my column names since they all have underscores and break LaTeX.

推荐答案

一切都简单多了.在 fixed("_") 的帮助下,将 literal 字符串替换为 literal 字符串,不需要正则表达式.

It is all much easier. Replace literal strings with literal strings with the help of fixed("_"), no need for a regex.

> library(stringr) > s <- "foo_bar_baz" > str_replace_all(s, fixed("_"), "\\_") [1] "foo\\_bar\\_baz"

如果你使用cat:

> cat(str_replace_all(s, fixed("_"), "\\_")) foo\_bar\_baz>

您会看到结果中实际上有 1 个反斜杠.

You will see that you actually have 1 backslash in the result.

更多推荐

替换下划线“

本文发布于:2023-10-31 18:22:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1546901.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:下划线

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!