Split string into substrings on one or more whitespaces

前端 未结 2 1780
南旧
南旧 2020-12-11 05:55

I want to split a string into several substrings at those positions where one or more whitespaces (tab, space,...) occur. In the documentation of strsplit() it says, that sp

相关标签:
2条回答
  • 2020-12-11 06:38

    Try

    strsplit(test, '\\s+')
    [[1]]
    [1] "123"    "nnn"    "ffffdffffd"
    

    \\s will match all the whitespace characters.

    0 讨论(0)
  • 2020-12-11 06:54

    [:space:] must be placed inside a character class [] to make it works, i.e. [[:space:]]. [:space:] on its own will be interpreted as a character class consisting of :, s, p, a, c, e.

    strsplit(test, "[[:space:]]+")
    

    Note that by default strsplit will use POSIX ERE, which results in locale-dependent interpretation of [:space:].

    In PCRE (Perl Compatible Regular Expression), [:space:] is locale-independent and is equivalent to \p{Xps}. Therefore, you might want to enable perl flag if you want consistent behavior across different locales.

    If you only want to collapse all spaces (ASCII 32) and want to leave the horizontal tabs \t and new line characters \n alone, OR you can assume that the text contains only space (ASCII 32) as spacing character:

    strsplit(test, " +")
    
    0 讨论(0)
提交回复
热议问题