-1

I have a string like so

This is a (Lock)item response(Unlock) and (Lock)request(Unlock)

I need to get all the strings between the prefix (Lock) and suffix (Unlock)

I need to get

  1. item response
  2. request

I am working in c# and have tried the following

  1. (?:(Lock))(.*)(?:(Unlock))

  2. (?<=(Lock))(.*)(?=(Unlock))

Not sure what to put in the middle part in place of (.*)

abhaybhatia
  • 599
  • 1
  • 7
  • 16
  • 1
    You need to make it non-greedy `.*?` – juharr Mar 31 '18 at 12:34
  • can u check my answer and see if it meets your requirements ? – Software Dev Mar 31 '18 at 12:40
  • @zackraiyan: Thank you for you answer Sir but I was looking for something more generic instead of what would work for this exact string – abhaybhatia Mar 31 '18 at 12:45
  • But why wouldn't my solution work if you have `(lock)` ,`(unlock)` in ur string ?? – Software Dev Mar 31 '18 at 12:48
  • In .NET regex, (?>([^(]*)) seems good in the place of (.*). Then full regex would be (?<=\\(Lock\\))(?>([^(]*))(?=\\(Unlock\\)) http://regexstorm.net/tester?p=%28%3f%3C%3d\%28Lock\%29%29%28%3f%3E%28[^%28]*%29%29%28%3f%3d\%28Unlock\%29%29&i=This+is+a+%28Lock%29item+response%28Unlock%29+and+%28Lock%29request%28Unlock%29 – Thm Lee Mar 31 '18 at 16:55

1 Answers1

3

Regular expression: (?:\(Lock\))(.*?)(?:\(Unlock\))

Example code in C#:

var r = new Regex(@"(?:\(Lock\))(.*?)(?:\(Unlock\))");
MatchCollection mc = r.Matches("This is a (Lock)item response(Unlock) and (Lock)request(Unlock)");

for(int i = 0; i < mc.Count; i++)
{
    // Groups[0] always contains the whole match
    // Groups[1] contains the capturing match
    Console.WriteLine(mc[i].Groups[1].Value);
}

Result:

enter image description here