Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# regex to extract groups from input

Tags:

c#

regex

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?

like image 348
Chris Avatar asked Nov 27 '25 02:11

Chris


1 Answers

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.

like image 52
Matthew Hazzard Avatar answered Nov 28 '25 14:11

Matthew Hazzard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!