Regex split string but keep separators

Posted by rwwilden on Stack Overflow See other posts from Stack Overflow or by rwwilden
Published on 2010-05-26T06:25:46Z Indexed on 2010/05/26 6:31 UTC
Read the original article Hit count: 1056

Filed under:
|
|

I'd like to do a Regex.Split on some separators but I'd like to keep the separators. To give an example of what I'm trying:

"abc[s1]def[s2][s3]ghi" --> "abc", "[s1]", "def", "[s2]", "[s3]", "ghi"

The regular expression I've come up with is new Regex("\\[|\\]|\\]\\["). However, this gives me the following:

"abc[s1]def[s2][s3]ghi" --> "abc", "s1", "def", "s2", "", "s3", "ghi"

The separators have disappeared (which makes sense given my regex). Is there a way to write the regex so that the separators themselves are preserved?

© Stack Overflow or respective owner

Related posts about c#

Related posts about regex