RegEx to get executable path from path which contains path and arguments

Darren Rose 496 Reputation points
2023-12-09T15:50:42.8966667+00:00

Hi

Trying to use RegEx (in VB.NET app) to parse a Win32_Service PathName to just get the path without any arguments

The below works well in most cases:

 Dim ExecutablePath = Regex.Replace(PathName, "^""([^""])"".$", "$1")

e.g. for

"C:\Program Files\AVG\Antivirus\AVGSvc.exe" /runassvc

but doesn't work if first part isn't in quotes e.g.

C:\WINDOWS\system32\SearchIndexer.exe /Embedding

Can someone please help me improve the RegEx so it works for both? and would return

"C:\Program Files\AVG\Antivirus\AVGSvc.exe" for first example

and

C:\WINDOWS\system32\SearchIndexer.exe for second example

Thank you

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,889 questions
{count} votes

Accepted answer
  1. Viorel 122.2K Reputation points
    2023-12-09T16:58:02.5966667+00:00

    Check an example:

    Dim PathName = """C:\Program Files\AVG\Antivirus\AVGSvc.exe"" /runassvc"
    'Dim PathName = "C:\WINDOWS\system32\SearchIndexer.exe /Embedding"
    
    Dim ExecutablePath = Regex.Match(PathName, "^(""(?<path>[^""]+)""|(?<path>\S+))").Groups("path").Value
    
    Console.WriteLine(ExecutablePath)
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.