ruby - What regex can I use to split a string into words but keep phrases in round brackets together? -
i'd split string this:
my_string = "i want split (these should stay together) correctly"
and have following result:
["i", "want", "to", "split", "this", "(these should stay together)", "correctly"]
i tried this:
my_string.split(/(?=[^\(]){1,} (?=[^\)]){1,}/)
but elements inside round brackets separated. how can achieve this?
split
wrong tool here. use scan
.
my_string.scan(/\([^)]*\)|\s+/) # => ["i", "want", "to", "split", "this", "(these should stay together)", "correctly"]
if balanced parentheses can adjacent other non-space characters, want put together, might want one, works more generally:
my_string.scan(/(?:\([^)]*\)|\s)+/)
in general, when delimiters can expressed in simple pattern, use split
. when content can expressed in simple pattern, use scan
.
Comments
Post a Comment