Sean21735
Sean21735

Reputation: 35

Powershell regular expression query

So far i have come up with below,

$String = "[EXTERNAL] +^ test 1"

OR

$String = "+^ RE: test 2"

if ( ($String -match "^\[EXTERNAL]\s\+\^") -or ($String -match "^\+\^") ) { write-host "Match" }

Question - How can I match below correctly?

$String =  "FW: [EXTERNAL] +^ test 2"

So any string containing "+^" BUT NOT "^\[EXTERNAL]\s\+\^" OR "^\+\^"

Any assistance appropriated ..

Upvotes: 2

Views: 83

Answers (1)

briantist
briantist

Reputation: 47802

If I understand you correctly, you want to match any string that:

  • contains +^ AND
  • does not begin with +^ AND
  • does not begin with [EXTERNAL] +^

Hopefully that's correct...

So for that I might do something like this:

$tests = @(
    "[EXTERNAL] +^ test 1"
    "+^ RE: test 2"
    "FW: [EXTERNAL] +^ test 2"
)

foreach ($inp in $tests) {
    if ($inp -match '\+\^' -and $inp -notmatch '^(?:\+\^|\[EXTERNAL\]\s\+\^)') {
        Write-Host "Test case '$inp' matched"
    }
    else {
        Write-Host "Test case '$inp' did not match"
    }
}

It is possible to do with a single regex, but that is often more complicated when you have a whole programming language at your fingertips, so I recommend using two conditionals like this (or 3 if you want to split the second one up).

Upvotes: 1

Related Questions