0

Could you tell me please, why there is an empty element in the vector after parsing a string?

What I enter:

a <- "--key1 = value1 --key2 = value2 --key3 = value3 --switch.1 --switch.2"
unlist(strsplit(a, split = "--"))

What I get:

[1] ""               "key1 = value1 " "key2 = value2 " "key3 = value3 "
[5] "switch.1 "      "switch.2"

And one more question: is it posible to choose only those elements from the vector, that have "=" (any certain letter) in them?

Thank you in advance!

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
SpikeBZ
  • 17
  • 7
  • 2
    I think [this post](http://stackoverflow.com/questions/15575221/why-does-strsplit-use-positive-lookahead-and-lookbehind-assertion-matches-differ) is *exactly* what you are looking for. – Arun Jun 12 '13 at 20:37
  • `v[grep("=", v)]` for your second question, where `v` is your vector – eddi Jun 12 '13 at 20:59

2 Answers2

4

You split the string with "--" being the delimiter. Since the very first characters in your input string are "--", conceptually you have an empty substring first, then the delimiter, then the rest of the string, etc. That's why the first element in the result array is an empty string.

3

From ?strsplit

 repeat {
    if the string is empty
        break.
    if there is a match
        add the string to the left of the match to the output.
        remove the match and all to the left of it.
    else
        add the string to the output.
        break.
}

So the first entry has "" to the left and that's why you're picking it up. You can always subset after the split on !="".

Tommy Levi
  • 771
  • 5
  • 12