Reputation: 263
Trying to select a string that returns words and numbers without erasing the rest of the output.
Right now I have the following:
$files = @'
Associations : 1, 2, 3, 4
Transactions: 20, 21, 22
Associations : 5, 6, 7, 8
Transactions, 99, TRANS12, TRANS13, 97
@'
$blob = $files -split '\r?\n'
$array = @()
[bool]$transBool = $false
$blob | ForEach-Object {
if ($_ -match ':') {
if ($_ -match '(Transactions)' -or $_ -match '(Tr)' -or $_ -match '(Trans)') {
$Trans = ($_ -split ':')[-1].TrimStart(",").TrimEnd(",")
$trans = $Trans -split ',' -replace " ", "" | select -Unique
$transBool = $true
} elseif ...
if ($Trans -match '[A-Z]') {
$transBool = $true
$obj = New-Object PSObject -Property @{
TransactionsAugust= $Trans
$output = "{0}
`Transactions for August : {1}" -f $output,
(($array.TransactionsAugust | Where-Object {$_ -like "[A-Z]*" -like "[0-9]" } | select -Unique) -join ",")
Write-Host $output
I'm able to pull all the Transactions that include the word TRANS on my output, but its also getting rid of 99 and 97 for example.
Goal: String is able to capture TRANS12, TRANS13 and return into a category named Transactions for August. Transactions 99 and 97 will be pulled out into a different category, called into another array.
Upvotes: 0
Views: 300
Reputation: 23763
Based on the variable definitions in the answer from Lee_Dailey
You might simplify the matching using the Select-String
cmdlet to retrieve the concerned values:
$InStuff | Select-String $TargetPattern -AllMatches | Foreach-Object {$_.Matches.Value}
Note: the syntax $_.Matches.Value
(called "property enumeration") requires PSv3 or higher,
for PSv2 use the Select-Object -ExpandProperty
cmdlet parameter.
Upvotes: 2
Reputation: 7489
i am not good with strictly regex solutions [blush] , so this uses a very simple regex pattern. if you can get a regex master to give you a complex pattern, it will likely be faster.
what the code does ...
trans
and one-or-more digits. -match
works on a collection to get any line that contains the target pattern ,
[space and then comma] $TargetItems
collection here's the code ...
# fake reading in a text file
# in real life, use Get-Content
$InStuff = @'
Associations : 1, 2, 3, 4
Transactions: 20, 21, 22
Associations : 5, 6, 7, 8
Transactions, 99, TRANS12, TRANS13, 97
'@ -split [System.Environment]::NewLine
$TargetPattern = 'trans\d{1,}'
$TargetItems = ($InStuff -match $TargetPattern -split ', ').
Trim().
Where({
$_ -match $TargetPattern
})
$TargetItems
output ...
TRANS12
TRANS13
Upvotes: 1