我在下面的regexstorm(.NET引擎)中测试了此regex,它可以工作,但是在PowerShell(v2)中,它不起作用...为什么?
$str = 'powershell is rock powershell is not rock'
$re = [regex]'@
(?xmin)
^
(
(?> [^i]+ | \Bi | i(?!s\b) )*
\bis\b
){2}
(?> [^i]+ | \Bi | i(?!s\b) )*$
'@
$re.matches($str)
# not return value why ?
最佳答案
2个问题
1.错别字:
$re = [regex]'@
...
'@
应该$re = [regex]@'
...
'@
2.空格当您使用诸如此类的here字符串时,行开头的空格很重要!您正在使其成为表达式的一部分。试试这个:
$str = 'powershell is rock powershell is not rock'
$re = [regex]@'
(?xmin)
^
(
(?> [^i]+ | \Bi | i(?!s\b) )*
\bis\b
){2}
(?> [^i]+ | \Bi | i(?!s\b) )*$
'@
$re.matches($str)
# not return value why ?
发布编辑阅读您的评论后,您似乎正在尝试匹配包含
is
单词的2个实例的字符串(不多不少)。我建议使用更多的代码和更少的正则表达式来做到这一点:
$s1 = 'powershell is rock powershell is not rock'
$s2 = 'powershell is what powershell is vegetable is not'
$s3 = 'powershell is cool'
$re = [regex]'\bis\b'
$re.matches($s1).captures.count
$re.matches($s2).captures.count
$re.matches($s3).captures.count
一个更简单的正则表达式,您可以简单地测试$re.matches($str).captures.count -eq 2
(或-ne 2
)。
关于regex - 正则表达式可以在所有.net引擎中在线工作,而不能在Powershell中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26496036/