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

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,604 questions
{count} votes