Home > other >  Regex find only 1 occurrence issue
Regex find only 1 occurrence issue

Time:01-12

I need to find line :

echo "PB702101 not executed"

in:

if test ${csis_batch_completion} -le ${csis_batch_warning} ;then
  echo "Running PB702101"
  run ${csis_obj}/PB702101
  display_completion
else
  echo "PB702101 not executed"
fi

I am currently using:

^(?!#)..echo ""((?!""))(\b.*?) not executed""$

but I keep getting :

  echo "Running PB702101"
  run ${csis_obj}/PB702101
  display_completion
else
  echo "PB702101 not executed"

How do I get only the last occurrence of echo with "XXXX not executed"?

CodePudding user response:

You can try this. It excludes all preliminary text, thereby getting the last one only.

@"(?s)echo[ ]""\w [ ]not[ ]executed""(?!.*echo[ ]""\w [ ]not[ ]executed"")"

https://regex101.com/r/TTTmwS/1

CodePudding user response:

With the following regex you'll match the whole string with the capturing group holding the code (PB702101 in your example) that follows the latest echo line:

. echo\s "(. ?)not executed"

And this is the snippet to run it with c#:

string input = 
 "if test ${csis_batch_completion} -le ${csis_batch_warning} ;then\n"  
 "  echo \"Running PB702101\"\n"  
 "  run ${csis_obj}/PB702101\n"  
 "  display_completion\n"  
 "else\n"  
 "  echo \"PB702101 not executed\"\n"  
 "fi";
        
string pattern = @". echo\s ""(. ?)not executed""";
Match match = Regex.Match(input, pattern);
if (match.Success)
  Console.WriteLine("Capturing Group: "   match.Groups[1].Value);
else
  Console.WriteLine("No match found.");

https://dotnetfiddle.net/SF5luh

  • Related