I would like to split a string using a regular expression in Dart, and include the matching delimiters in the resulting list. For example, the string 123.456.789
should result in [ 123, ., 456, ., 789 ]
.
The behaviour of split
in languages like C#, JavaScript, Python and Perl can be achieved by including the delimiters in capturing parentheses. However, this doesn’t seem to work in Dart.
The following regex can be used to split a string with single delimiter, with lookbehind and lookahead: ((?<=\.)|(?=\.))
. For multiple delimiters, the regex should be ((?<=\.|;)|(?=\.|;))
.
print("123.456.789;abc;.xyz.;ABC".split(new RegExp(r"((?<=\.|;)|(?=\.|;))")));
This yields [ 123, ., 456, ., 789, ;, abc, ;, ., xyz, ., ;, ABC ]
.