我如何测试' - '是否存在但不在'['和']'字符之间?

时间:2016-03-25 20:43:21

标签: .net regex powershell

我如何测试' - '是否存在但不在'['和']'字符之间?

例如:

AFR-SADKJ :匹配

safkdsjfs [9-0] :跳过(beacause -exists但有[之前和之后]

你可以建议吗? 谢谢!

3 个答案:

答案 0 :(得分:3)

-notmatch运算符与正方形表达式之间的连字符匹配的正则表达式结合使用:

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

请注意,您需要进行两次检查才能生效:一次确认是否存在连字符,第二次检查是否在方括号之间。否则,对于不包含连字符的字符串,您会收到误报。

如果您经常需要此检查,可能需要将其包装在函数中:

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

答案 1 :(得分:1)

-(?![^[]*])

这是工作DEMO

答案 2 :(得分:1)

尝试以下RegEx:

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

Live Demo on Regex101

工作原理:

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