Note that there are some explanatory texts on larger screens.

plurals
  1. POTokenizing with RegEx when delimiter can be in token
    primarykey
    data
    text
    <p>I'm parsing some input in C#, and I'm hitting a wall with RegEx processing.</p> <p>A disclaimer: I'm not a regular expression expert, but I'm learning more.</p> <p>I have an input string that looks like this:</p> <p>ObjectType [property1=value1, property2=value2, property3=AnotherObjectType [property4=some value4]]</p> <p>(a contrived value, but the important thing is that these can be nested).</p> <p>I'm doing the following to tokenize the string:</p> <pre><code>Regex Tokenizer = new Regex(@"([=\[\]])|(,\s)"); string[] tokens = Tokenizer.Split(s); </code></pre> <p>This gets me about 98% of the way. This splits the string on known separators, and commas followed by a whitespace.</p> <p>The tokens in the above example are:</p> <pre><code>ObjectType [ property1 = value1 , property2 = value2 , property3 = AnotherObjectType [ property4 = some value4 ] ] </code></pre> <p>But I have two issues:</p> <p>1) The property values can contain commas. This is a valid input:</p> <pre><code>ObjectType [property1=This is a valid value, and should be combined,, property2=value2, property3=AnotherObjectType [property4=value4]] </code></pre> <p>I would like the token after property1= to be:</p> <pre><code>This is a valid value, and should be combined, </code></pre> <p>And I'd like the whitespace inside the token to be preserved. Currently, it's split when a comma is found.</p> <p>2) When split, the comma tokens contain whitespace. I'd like to get rid of this if possible, but this is a much less important priority.</p> <p>I've tried various options, and they have all gotten me partially there. The closest that I've had is this:</p> <pre><code> Regex Tokenizer = new Regex(@"([=\[\]])|(,\s)|([\w]*\s*(?=[=\[\]]))|(.[^=]*(?=,\s))"); </code></pre> <p>To match the separators, a comma followed by a whitepace, word charaters followed by a whitespace before a literal, and text before a comma and whitespace (that doesn't include the = sign).</p> <p>When I get the matches instead of calling split, I get this:</p> <pre><code>ObjectType [ property1 = value1 , property2 = value2 , property3 = AnotherObjectType [ property4 = value4 ] ] </code></pre> <p>Notice the missing information from property4. More complex inputs sometimes have the close brackets included in the token, like this: value4] I'm not sure why that's happening. Any ideas on how to improve upon this?</p> <p>Thanks, Phil</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload