Rice Rice - 2 years ago 175
C# Question

C# greedy regular expression including match text

I currently have the string:


I tried:

splitty = Regex.Split(lineText,@"[\,]+\s*(?>arg_){1}?");

and received:

[0]: "CL,UP_REMOVE_LINE,#global_session_id"
[1]: "stage=false"
[2]: "project_id=-1,#global_line_id"
[3]: "activity_id=-1"
[4]: "mode=1"
[5]: "line_id=#global_line_id"
[6]: "session_id=-1"

I am splitting by at least one comma, followed by arbitrary white space followed by the "arg_" delimiter, but is there any way to keep the "arg_" portion intact, i.e. indicies [1-6]?

Answer Source

Use a positive lookahead (to check the presence of, but not consume, thus leaving it in the split chunks) instead of an atomic group (that is still consumed, and thus is removed when using Split):


See the regex demo

Note you do not need to put the comma into a character class, nor do you need to escape the comma.

enter image description here

Also, {1}? = {1} and is totally redundant (you may always remove it since this {1} is always implied (i.e. abc = a{1}b{1}c{1})).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download