简体   繁体   中英

Regular Expression (in C#) that starts with a string, but matches everything that is after the last occurrence …

I'm trying to parse in C# some 'hard-coded' variable initializations (from a custom language) from many files into a db, but I'm having problems:

Sample Code to Parse #1 >>>

ArrayName[ArrayIndexVariable].arrayPropertyNameHex            = $A3

I'm trying to use the regular expression:

string strRegExCriteria = @"^sArrayName\[ArrayIndexVariable\]\.arrayPropertyNameHex.+= ?(.+?)$";

Which returns .Success, however:

matchRegExCriteria.Groups[1].Value.ToString().Length.ToString();

... is equal to 0? ...


Sample Code to Parse #2 >>>

ArrayName[ArrayIndexVariable].arrayPropertyNameInt            = 6942

I'm trying to use the regular expression:

string strRegExCriteria = @"^sArrayName\[ArrayIndexVariable\]\.arrayPropertyNameInt.+?(\d+)$";

Which also returns .Success, however:

matchRegExCriteria.Groups[1].Value.ToString().Length.ToString();

... is equal to 0? ...

Any ideas?

I think your problem is that you're using the greedy qualifier in your regex. In your regex (broken up for readability):

string strRegExCriteria = @"^sArrayName\[ArrayIndexVariable\]\." +
  @"arrayPropertyNameHex.+= ?(.+?)$";

You have .+ after arrayPropertyNameHex , which is "greedily" matching everything to the end of the line, so your capture is never getting hit. Just change it to the non-greedy match ( +? ), and it should work better:

string strRegExCriteria = @"^sArrayName\[ArrayIndexVariable\]\." +
  @"arrayPropertyNameHex.+?= ?(.+?)$";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM