regex可以在所有的.net引擎中联机运行,但不能在powershell中运行



我在下面的regexstorm(.NET引擎)中测试了这个regex,它工作了,但在PowerShell(v2)中不工作。。。为什么?

$str = 'powershell is rock powershell is not rock'
$re = [regex]'@
 (?xmin)
  ^
  (
   (?> [^i]+ | Bi | i(?!sb) )*
   bisb
  ){2}
   (?> [^i]+ | Bi | i(?!sb) )*$
'@
$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(?!sb) )*
bisb
){2}
(?> [^i]+ | Bi | i(?!sb) )*$
'@
$re.matches($str)
# not return value why ?

发布编辑

在阅读了您的评论后,您似乎正在尝试匹配一个包含单词is的两个实例的字符串(不多不少)。

我建议使用更多的代码和更少的正则表达式:

$s1 = 'powershell is rock powershell is not rock'
$s2 = 'powershell is what powershell is vegetable is not'
$s3 = 'powershell is cool'
$re = [regex]'bisb'
$re.matches($s1).captures.count
$re.matches($s2).captures.count
$re.matches($s3).captures.count

一个简单得多的正则表达式,您可以简单地测试是否为$re.matches($str).captures.count -eq 2(或-ne 2)。

最新更新