Ad
R String Split On Parentheses, Keeping The Parentheses In The Split With Its Content
I am trying to split strings of a format
x <- "A(B)C"
where A, B and C could be empty strings or any sets of characters except for parentheses. The parentheses are always there - I want to keep them around the characters they enclose, so that the result would be:
"A" "(B)" "C"
So far my best try was:
strsplit(x, "(?<=\\))|(?=\\()", perl = TRUE)
[[1]]
[1] "A" "(" "B)" "C"
but that keeps the opening parenthesis separate. Any ideas?
Ad
Answer
You can use
x <- "A(B)C"
library(stringr)
str_extract_all(x, "\\([^()]*\\)|[^()]+")
See the R demo and the regex demo. Details:
\([^()]*\)
- a(
, zero or more chars other than(
and)
and then)
|
- or[^()]+
- one or more chars other than(
and)
.
Ad
source: stackoverflow.com
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page
Ad