[R] String manipulation

William Dunlap wdunlap at tibco.com
Mon Dec 8 22:20:30 CET 2014


Actually, the zero-length look-ahead expression is enough to get the job
done:

> strsplit(c(":sad", "happy:", "happy:sad", ":happy:sad:subdued:"),
split="(?=:)", perl=TRUE)
[[1]]
[1] ":"   "sad"

[[2]]
[1] "happy" ":"

[[3]]
[1] "happy" ":"     "sad"

[[4]]
[1] ":"       "happy"   ":"       "sad"     ":"       "subdued" ":"



Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Mon, Dec 8, 2014 at 1:13 PM, William Dunlap <wdunlap at tibco.com> wrote:

> strsplit(split=":") does almost what you want, but it omits the colons
> from the output.  You can use perl zero-length look-ahead and look-behind
> operators in the split argument to get the colons as well:
>
> > strsplit(c(":sad", "happy:", "happy:sad"), split="(?<=:)|(?=:)",
> perl=TRUE)
> [[1]]
> [1] ":"   "sad"
>
> [[2]]
> [1] "happy" ":"
>
> [[3]]
> [1] "happy" ":"     "sad"
>
>
>
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
>
> On Mon, Dec 8, 2014 at 9:08 AM, Gang Chen <gangchen6 at gmail.com> wrote:
>
>> I want to do the following: if a string does not contain a colon (:),
>> no change is needed; if it contains one or more colons, break the
>> string into multiple strings using the colon as a separator. For
>> example, "happy:" becomes
>>
>> "happy" ":"
>>
>> ":sad" turns to
>>
>> ":" "sad"
>>
>> and "happy:sad" changes to
>>
>> "happy" ":" "sad"
>>
>> How to do this?
>>
>> Thanks,
>> Gang
>>
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list