Reputation: 2282
I tested this regex below in regexstorm (.NET engine) and it worked, but in PowerShell (v2) it doesn't work...why ?
$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 ?
Upvotes: 1
Views: 153
Reputation: 47802
$re = [regex]'@
...
'@
should be
$re = [regex]@'
...
'@
When you use a here string like that, the whitespace at the beginning of the lines counts! You're making it part of the expression. Try this:
$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 ?
After reading your comment, it seems like you're trying to match a string that contains 2 instances of the word is
(no more no less).
I recommend doing this with more code and less regex:
$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
A much simpler regex, and you can simply test if $re.matches($str).captures.count -eq 2
(or -ne 2
).
Upvotes: 3