Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I would like to write pattern for regular expression which will maintain the sequence of word.

For Example:

I have one string like below:

string input="I visited this place with my friends twice. Normal outdoor sitting but yet pleasing. Food is very delicious and sumptuous. However they highly lack in Service which they need to improve a lot. On both my visit they failed to deliver the complete order and on asking twice - thrice, they finally came after half and hour and said that \" sorry we didn't prepare that, shall we prepare it now\". It was pretty disappointing as it happened repeatedly. I would have giving this place a 5 star but due to their poor service I will give them just 2 Stars."

    string strPattern = "(visit(.*?) this place)";
    Match matchResult = Regex.Match(input, strPattern, RegexOptions.IgnoreCase);
     while(matchResult.Success) {
     Console.WriteLine(matchResult.Value);
     matchResult = matchResult.NextMatch();
    }


When i console it this gives the output like

1. visited this place
2. visit they failed to deliver the complete order and on asking twice - thrice,
they finally came after half and hour and said that " sorry we didn't prepare
that, shall we prepare it now". It was pretty disappointing as it happened
repeatedly. I would have giving this place

So, The first output(visited this place) is fine.
But the second one not proper because it is taking the part of input string starting from word "visit" and ends with "this place".

I need the output like visit this place,visiting this place,visited this place etc..

So, for the above input string output should be this only
1. visited this place

The pattern should be in this manner so that it will maintain the sequence between the word also.

Thanks.
Posted
Updated 27-Aug-15 16:55pm
v2
Comments
Andy Lanng 27-Aug-15 10:08am    
VERY loaded / open ended question, there. Could you help us by being more specific and telling us what this is for and how you intend to use it, please ^_^

1 solution

The problem is that "visit...this place" occurs twice in the input phrase. So you have two options:
1) Check each match afterwards and discard "improper" ones
Or
2) Limit the length of of the "valid" input to prevent the second being a match at all.
For that try something like:
(visit(.{1,10}?)\sthis\splace)
Where 10 is the max length you will accept.
 
Share this answer
 
Comments
Anant K Sinha 27-Aug-15 22:43pm    
Great...It works. Thanks.
OriginalGriff 28-Aug-15 4:22am    
You're welcome!

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