简体   繁体   English

Powershell正则表达式如何工作?

[英]How does this Powershell Regex work?

'<Relation From="701047080" ObjectNumber="166543300" Output="77" To="464616324">' -match '(?<=Output=")[^"]*'

$matchs then contains 77? $matchs然后包含77?

Which is what I want, I just don't understand why it works? 这就是我想要的,我只是不明白为什么它有效?

I've found stuff saying I could: 我找到的东西说我可以:

match '(?<NAME>Some regex)'

But I have no Idea what '(?<=' does? And I would REALLY like to understand the syntax... 但我不知道'(?<='是什么?我真的很想理解语法......

I actually need to pull out the value of Output and To both... And only have powershell on the system I need to do this on... 我实际上需要提取Output和To两者的值...并且只需要在系统上使用powershell我需要这样做......

The expression (?<=Output=") is a lookbehind . It matches only immediately after the string Output=" . 表达式(?<=Output=")是一个lookbehind 。它只在字符串Output="之后立即匹配。

The expression [^"]* is a negated character class . It matches all characters until the next double-quote (or to the end of the string if there are no more double-quotes). 表达式[^"]*是一个否定的字符类 。它匹配所有字符,直到下一个双引号(如果没有双引号,则匹配字符串的结尾)。

The [^"]* says any number of characters other than " . [^"]*表示除"之外的任何数量的字符。

The [^"]* is the main expression. [^"]*是主要表达方式。

The (?<=Output=") is a lookbehind and makes sure that the main expression is following the expression in the lookbehind, in this case Output=" . (?<=Output=")是一个lookbehind,并确保主表达式跟随lookbehind中的表达式,在这种情况下Output=" The lookbehind expression is not included in the match lookbehind表达式不包含在匹配中

I don't think the regex is optimal. 我不认为正则表达式是最优的。

You could have used: 你可以使用:

'<Relation From="701047080" ObjectNumber="166543300" Output="77" To="464616324">' -match 'Output="(.*?)"'

(with the regex being as simple as Output="(.*?)" ) (正则表达式与Output="(.*?)"一样简单)

and got the 77 in $matches[1] $matches[1]得到77分$matches[1]

The regex was probably just complicated with the lookbehind to make the Output=" be not part of the match. It makes the regex more complex and reduces performance. All you need is the above regex and extract 77 with the appropriate group. 正则表达式可能只是复杂的外观使得Output="不是匹配的一部分。它使正则表达式更复杂并降低性能。所有你需要的是上面的正则表达式并用适当的组提取77。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM