regex - 正则表达式可以在所有.net引擎中在线工作,而不能在Powershell中工作?

标签 regex powershell

我在下面的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/

相关文章:

php - 验证 CSV 文件是否真的是 CSV 文件

java - 无法在 Java 中正确拆分字符串

powershell - 调用 Web 服务如何添加参数

regex - Postgres 正则表达式限制禁用字符和限制连续大写的数量

javascript - 正则表达式仅接受名称和数字

JavaScript - 通过多个正则表达式模式拆分字符串返回不需要的值

powershell - New-ScheduledTaskTrigger -AtLogon重复

powershell - 通过在 Windows 10 上提供管理员凭据,无需提升的 New-CimSession?

sql - 构建批量插入语句powershell to sql

PowerShell 输出文件