Home > Enterprise >  Is there a regex to capture a directory, without the whole line?
Is there a regex to capture a directory, without the whole line?

Time:07-12

I would like to try automating the compiling of a python app I made using PowerShell. In order to achieve, I have to get the directory name of where my python packages are installed as a variable. I'll use the exemple of matplotlib.

pip show matplotlib

This allows me to get the following:

Name: matplotlib
Version: 3.5.2
Summary: Python plotting package
Home-page: https://matplotlib.org
Author: John D. Hunter, Michael Droettboom
Author-email: [email protected]
License: PSF
Location: c:\users\bschmidt\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages
Requires: cycler, fonttools, kiwisolver, numpy, packaging, pillow, pyparsing, python-dateutil

Using select-string, I can manage to corner the desired line, containing the directory name.

Select-String -pattern "\bc:\\*\b"

It gives me the following line:

Location: c:\users\bschmidt\appdata\local\packages\pythonsoftwarefoundation.pyt ##hon.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages

Now comes my problem: how can I isolate c:\users\bschmidt\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages ?

CodePudding user response:

You might for example use a capture group matching 1 or more non whitespace chars:

^Location:\s*(\S )'

Regex demo

Example code

$Str = @"
Name: matplotlib
Version: 3.5.2
Summary: Python plotting package
Home-page: https://matplotlib.org
Author: John D. Hunter, Michael Droettboom
Author-email: [email protected]
License: PSF
Location: c:\users\bschmidt\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages
Requires: cycler, fonttools, kiwisolver, numpy, packaging, pillow, pyparsing, python-dateutil
"@

$Pattern = '(?m)^Location:\s*(\S )'
$Str -match $Pattern | Out-Null
$Matches[1] # First capturing group

Output

c:\users\bschmidt\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages

Or more specific, matching c:\ followed by the rest of the line:

^Location:\s*(c:\\.*)

Regex demo

  • Related