The pattern worked for my case. However in scenarios where there is space in the site name, only the last name is getting updated.
Ex: http://webapp/sites/site abc - only "abc" is being extracted instead of "site abc". Can the pattern be modified for this by any chance?
sure, it can.
if you really get a space in URL then eg. following pattern should work.
but I would say you will rather get your URL formatted like http://webapp/sites/site%20abc
in such case you might use