Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string after comma without trailing whitespace

As the title already says, I want to split this string

strsplit(c("aaa,aaa", "bbb, bbb", "ddd , ddd"), ",")

to that

[[1]]
[1] "aaa" "aaa"

[[2]]
[1] "bbb, bbb"

[[3]]
[1] "ddd , ddd"

Thus, the regular expression has to consider that no whitespace should occur after the comma. Could be a dupe, but was not able to find a solution by googling.

like image 202
Roman Avatar asked Feb 23 '26 04:02

Roman


1 Answers

regular expression has to consider that no whitespace should occur after the comma

Use negative lookahead assertion:

> strsplit(c("aaa,aaa", "bbb, bbb", "ddd , ddd"), ",(?!\\s)", perl = TRUE)
[[1]]
[1] "aaa" "aaa"

[[2]]
[1] "bbb, bbb"

[[3]]
[1] "ddd , ddd"

,(?!\\s) matches , only if it's not followed by a space

like image 61
Avinash Raj Avatar answered Feb 25 '26 18:02

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!