Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have few user inputs which I am trying to compare via MatchCollection with different patterns I have i.e

C#
string user = "\b(?:I|would|like|to|see|id|of|bought|good)\b";



but When I am matching string

C#
string pattern = "^(?=.*\bgoods?|items?|things?\b)(?=.*\bbought\b)(?=.*\bid\b)(?=.*\btest\b).*$";

MatchCollection mat = Regex.Matches(pattern , user );

foreach (var item in mat)
{
    Console.WriteLine(item.ToString());
}


When matching the two above, the match collection only yields/collects match for (id, bought) but ignores "goods" from the first block of pattern. It seems to be ignoring **?** lookahead mentioned goods?|items?|things?.

Any suggestions.


Thanks
Posted
Updated 6-Jul-14 15:01pm
v2

1 solution

Hi,

Change your expression to this:

C#
string pattern = "(?=.*\bgoods\b|\bitems\b|\bthings?\b)(?=.*\bbought\b)(?=.*\bid\b)(?=.*\btest\b).*";


Putting a ? after the 's' in 'things?' will catch both thing and things.

You need to have word boundaries around each word in the optional list.
(You also misspelled goods as good in your user input, but I assume you mean goods.)
 
Share this answer
 
v2
Comments
Member 10237446 9-Jul-14 5:46am    
Thanks George for the solution. Could you also please guide if in your given solution there is a possibility to use Any Character or "?" so if in pattern we have .i.e. string pattern = "(?=.*\bgoods\b|\bitems\b|\bthings?\b) and some writes only "thing" (ignoring the plural s at the end), it would still match. Thanks in advance.
George Jonsson 9-Jul-14 6:43am    
I recommend this page http://www.regular-expressions.info/
(?=.*\bgood?\b|\bitems\b|\bthings?\b)(?=.*\bbought\b)(?=.*\bid\b)(?=.*\btest\b).*
Putting a ? after the 's' in 'things?' will catch both thing and things.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900