【问题标题】:R: Explode string but keep quoted text as a single wordR:分解字符串但将引用的文本保留为单个单词
【发布时间】: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 的答案要好得多

标签: r regex stringi


【解决方案1】:

一个简单的选择是使用scan:

> x <- scan(what = "", text = mystr)
Read 11 items
> x
 [1] "preceded by itself in quotation marks forms a complete sentence"
 [2] "preceded"                                                       
 [3] "by"                                                             
 [4] "itself"                                                         
 [5] "in"                                                             
 [6] "quotation"                                                      
 [7] "marks"                                                          
 [8] "forms"                                                          
 [9] "a"                                                              
[10] "complete"                                                       
[11] "sentence"  

【讨论】:

    猜你喜欢
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 2014-11-28
    • 2017-07-03
    • 1970-01-01
    • 2012-07-18
    相关资源
    最近更新 更多