pencilCake
pencilCake

Reputation: 53263

How can I test if '-' exists but NOT between character '[' and ']'?

How can I test if '-' exists but NOT between character '[' and ']' ?

For example:

AFR-SADKJ : Match

safkdsjfs[9-0] : Skipped (beacause -exists but there is [ somewhere before and ] after

Can you advise? Thanks!

Upvotes: 1

Views: 49

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200373

Use the -notmatch operator in combination with a regular expression that matches a hyphen somewhere between square brackets:

PS C:\> $re = '\[.*-.*\]'
PS C:\> $s1 = 'AFR-SADKJ'
PS C:\> $s2 = 'safkdsjfs[9-0]'
PS C:\> $s3 = 'foobar'
PS C:\> $s1 -like '*-*' -and $s1 -notmatch $re
True
PS C:\> $s2 -like '*-*' -and $s2 -notmatch $re
False
PS C:\> $s3 -like '*-*' -and $s3 -notmatch $re
False

Note that you need two checks for this to work: one that confirms the presence of a hyphen and the second that checks if it's between square brackets. Otherwise you'd get false positives for strings that don't contain hyphens.

If you need this check frequently you may want to wrap it in a function:

function Test-Hyphen([string]$s) {
  $s -like '*-*' -and $s -notmatch '\[.*-.*\]'
}

Upvotes: 3

Kaspar Lee
Kaspar Lee

Reputation: 5596

Try the following RegEx:

(?!\[.*)-(?!.*\])

Live Demo on Regex101


How it works:

(?!\[.*)    # Do Not match if there is a [ then data
-           # Hyphen
(?!.*\])    # Do Not match if there is data then a ]

Upvotes: 1

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34170

-(?![^[]*])

Here is the working DEMO

Upvotes: 1

Related Questions