wehelpdox
wehelpdox

Reputation: 587

Get the next string after validating patterns using powershell

I have a text file and the contents can be:

debug --configuration "Release" \p corebuild

Or:

-c "Dev" debug 

And now I have to validate the file to see if it has any pattern that matches --configuration or -c and print the string next to it

How to achieve this in single command?

I tried below , but not sure how to extract only the release in the text , I only tried to see 1 pattern at a time

PS Z:\> $text = Get-Content 'your_file_path' -raw
PS Z:\> $Regex = [Regex]::new("(?<=\-\-configuration)(.*)")
PS Z:\> $Match = $Regex.Match($text)
PS Z:\> $Match.Value

 **Release /p net** 

Any help would be appreciated

Upvotes: 3

Views: 550

Answers (2)

mklement0
mklement0

Reputation: 438113

To complement Santiago's helpful answer with a PowerShell-only alternative:

Assuming that a matching line only ever contains --configuration OR -c, you can avoid the need for .NET API calls with the help of the -match operator, which outputs a Boolean ($true or $false) to indicate whether the input string matches, and also reports the match it captures in the automatic $Matches variable:

# Note: Omitting -Raw makes Get-Content read the file *line by line*.
Get-Content 'your_file_path' |
  ForEach-Object { # Look for a match on each line
    # Look for the pattern of interest and capture the
    # substring of interest in a capture group - (...) - 
    # which is later reflected in $Matches by its positional index, 1.
    if ($_ -match '(?:--configuration|-c) "(.*?)"') { $Matches[1] } 
  }

Note:

  • -match only every looks for one match per input string, and only populates $Matches if the input is a single string (if it is an array of strings, -match acts as a filter and returns the subarray of matching elements).

    • GitHub issue #7867 proposes introducing -matchall operator that looks for all matches in the input string.
  • See this regex101.com page for an explanation of the regex.

Upvotes: 1

Santiago Squarzon
Santiago Squarzon

Reputation: 60110

If I understand correctly and you only care about extracting the argument to the parameters and not which parameter was used, this might do the trick:

$content = Get-Content 'your_file_path' -Raw

$re = [regex] '(?i)(?<=(?:--configuration|-c)\s")[^"]+'
$re.Matches($content).Value

See https://regex101.com/r/d2th35/3 for details.

From feedback in comments --configuration and -c can appear together, hence Regex.Matches is needed to find all occurrences.

Upvotes: 3

Related Questions