Regex is not grabbing first non alphanumeric character

TCH 26 Reputation points
2022-11-29T01:13:26.547+00:00

I have a regex expression that is pulling correctly in all but one scenario. Given VAR1 is provided, it works fine. If VAR1 is NOT provided, then it will strip out the first special character of VAR2. VAR1, VAR3, VAR4 all pull if included in dictionaries as expected.

Text: Apples %BEANS% Oranges Pears

Works fine:

          var regexPattern =  
                string.Format(  
                    CultureInfo.InvariantCulture,  
                    @"  
                        (?:  
                                 (?:(?<VAR1>{0}(\w+\ ))\s+)?  
                                  (?:  
                                    (?<VAR2>[^,]+)  
                                    (?:[^\w,\&\'\+\-\@\/\*\!\#\\]+(?<VAR3>{0})\b)  
                                    (?:[^\w,\&\'\+\-\@\/\*\!\#\\]+(?<VAR4>{1})\b)  
                                 |  
                                 etc.....  

Result:
VAR1=Apples
VAR2=%BEANS%
VAR3=Oranges
VAR4=Pears

However, if VAR1 data is not provided, the result is:

Text: %BEANS% Oranges Pears

Result:
VAR1=Nothing (this is accurate)
VAR2=BEANS% (where did the preceding % go?)
VAR3=Oranges
VAR4=Pears

Developer technologies C#
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.