Reputation: 147
I want to extract anything between two colon's (inclusive of the colon's) in an arbitrary input using C#. Given
String input = "a:one:b:two:c:three:d";
I want
{string[3]}
[0]: ":one:"
[1]: ":two:"
[2]: ":three:"
Using
String[ ] inverse = Regex.Split( input, ":.*?:" );
I get the opposite of what I want...
{string[4]}
[0]: "a"
[1]: "b"
[2]: "c"
[3]: "d"
How can I inverse this or is there something more suitable than Regex.Split in this situation?
Upvotes: 3
Views: 212
Reputation: 1214
How about :[^:]+:
1. Match a colon
2. Followed by any non colon character one or more times.
3. Followed by a colon.
To get the set of matches use MatchCollection matches = Regex.Matches(blah, ":[^:]+:");
instead of Regex.Split
Regex's are concise and powerfull but I find myself writting just as many comments as I would code when using them.
Upvotes: 1
Reputation: 48775
How about you just use a regular split (on ':'), extract every second element, and then append the colons back on? I think you're overcomplicating this.
Upvotes: 0