walid toumi
walid toumi

Reputation: 2282

regex work in all .net engine online but not in powershell?

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

Answers (1)

briantist
briantist

Reputation: 47802

2 Problems

1. A typo:

$re = [regex]'@
...
'@

should be

$re = [regex]@'
...
'@

2. Whitespace

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 ?

Post Edit

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

Related Questions