1

in a text something like this, I need to be able to read the project code which is unique per text file.

devices           : 
meta              : @{Projectcode=rvmf99999}
public_keys       : @{Key=ssh-

select-string -pattern "rvmf" picks up the whole line, I just need rvmf and the digits after that.

1 Answer 1

1
# Sample input
$txt = @'
devices           : 
meta              : @{Projectcode=rvmf99999}
public_keys       : @{Key=ssh-
'@

$txt | Select-String 'rvmf\d+' | foreach { $_.Matches[0].Value } # -> 'rvmf99999'
  • Regex 'rvmf\d+' captures substring 'rvmf' followed by 1 or more (+) digits (\d).

  • The object output by Select-String has a .Matches property whose first entry's .Value property contains what the regex captured.

    • Specifically, the output objects are of type Microsoft.PowerShell.Commands.MatchInfo, which contains the input line (property .Line) as well as metadata about the source of the line and details about the regex-matching operation in the .Matches property.
    • Specifically, the .Matches property contains a collection of match-information objects; unless -AllMatches was passed to Select-Object, there will only be one element, however.
    • Each element of the .Matches collection is a System.Text.RegularExpressions.Match instance, whose .Value property contains what the regex captured as a whole.

Note: There is an upcoming feature - green-lighted, but not yet implemented as of PowerShell Core 7.0.0-preview.5 - that will greatly simplify the command:

# NOT YET IMPLEMENTED as of PowerShell Core 7.0.0-preview.5
$txt | Select-String 'rvmf\d+' -OnlyMatching # -> 'rvmf99999'

-OnlyMatching will only output the part of the line that was matched.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to hear it, @andrewjung; thanks for accepting - see my update re an upcoming feature that will greatly simplify your command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.