如何使用'|'进行strsplit字符,它的行为出乎意料? [英] How to strsplit using '|' character, it behaves unexpectedly?

查看:62
本文介绍了如何使用'|'进行strsplit字符,它的行为出乎意料?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在模式|"处分割一串字符

I would like to split a string of character at pattern "|"

但是

unlist(strsplit("I am | very smart", " | "))

[1] "I"     "am"    "|"     "very"  "smart"

gsub(pattern="|", replacement="*", x="I am | very smart")    

[1] "*I* *a*m* *|* *v*e*r*y* *s*m*a*r*t*"

推荐答案

问题是默认情况下 strsplit" | " 解释为正则表达式,其中 | 具有特殊含义(如或").

The problem is that by default strsplit interprets " | " as a regular expression, in which | has special meaning (as "or").

使用 fixed 参数:

unlist(strsplit("I am | very smart", " | ", fixed=TRUE))
# [1] "I am"       "very smart"

副作用是计算速度更快.

Side effect is faster computation.

stringr 替代:

unlist(stringr::str_split("I am | very smart", fixed(" | ")))

这篇关于如何使用'|'进行strsplit字符,它的行为出乎意料?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆