【发布时间】:2018-05-27 13:47:12
【问题描述】:
我遇到了这个问题: PHP explode the string, but treat words in quotes as a single word
和类似的处理使用正则表达式分解句子中的单词,用空格分隔,但保持引用的文本完整(作为单个单词)。
我想在 R 中做同样的事情。我试图将正则表达式复制粘贴到 stringi 包中的 stri_split 以及基础 R 中的 strsplit 中,但我怀疑正则表达式使用格式 R 无法识别。错误是:
错误:'\S' 是字符串中无法识别的转义...
期望的输出是:
mystr <- '"preceded by itself in quotation marks forms a complete sentence" preceded by itself in quotation marks forms a complete sentence'
myfoo(mystr)
[1] "preceded by itself in quotation marks forms a complete sentence" "preceded" "by" "itself" "in" "quotation" "marks" "forms" "a" "complete" "sentence"
尝试:strsplit(mystr, '/"(?:\\\\.|(?!").)*%22|\\S+/') 给出:
Error in strsplit(mystr, "/\"(?:\\\\.|(?!\").)*%22|\\S+/") :
invalid regular expression '/"(?:\\.|(?!").)*%22|\S+/', reason 'Invalid regexp'
【问题讨论】:
-
试试
\\S(对于R中正则表达式的任何反斜杠字符) -
你试过的正则表达式在哪里?为什么你的代码不在这个问题中?
-
"(?:[^"\\]|\\.)*"|\S+? 也适用于转义的双引号 -
@ctwheels,您建议的正则表达式提供与 OP 完全相同的错误。 Tensibai 关于反斜杠的评论也可以弥补这一点。
-
@r2evans I did test my answer in R and it does work。无论如何,我认为 A5C1D2H2I1M1N2O1R2T1 的答案要好得多