negative lookbehind(?<!\S)
在这种情况下使用:(?<!prefix)thing
以匹配不不对左前缀的事情。当你把它放在正则表达式的末尾,没有任何事情发生时,我认为它什么也不做。你可能打算把它放在左边,或者可能打算成为一个负面看前面,我不会猜测,我只是删除它的这个答案。
您错过了character classes的使用。 abc
寻找文字abc
,但将它们放在方括号内,并且[abc]
寻找任何字符a
,b
,c
。
- 使用它,可以将最后两行合并为一个:
[\n\t]
,它可以替换换行符或制表符。
您可以结合两个独立使用正则表达式的逻辑OR |
做一个匹配(什么也没有更换)规则:\s{2,100}|[\n\t]
- 匹配空格或换行或制表符。 (你可以使用OR两次而不是字符,fwiw)。
使用regex capture groups它允许您引用无论正则表达式匹配,而无需事先知道那是什么。
例如, "space bracket -> bracket"
和"space colon -> colon"
和"space comma -> comma"
都遵循一般模式"space (thing) -> (thing)"
。和尾随空格"(thing) space -> (thing)"
一样。
将带有字符类的捕获组合并为其余的行全部合并为一个。
例如
$a -replace " (:)", '$1' # capture the colon, replacement is not ':'
# it is "whatever was in the capture group"
$a -replace " ([:,])", '$1' # capture the colon, or comma. Replacement
# is "whatever was in the capture group"
# space colon -> colon, space comma -> comma
# make the space optional with \s{0,1} and put it at the start and end
\s{0,1}([:,])\s{0,1} #now it will match "space (thing)" or "(thing) space"
# Add in the rest of the characters, with appropriate \ escapes
# gained from [regex]::Escape('those chars here')
# Your original:
$a = (gc D:\css\1.css -Raw)
$a = $a -replace "\s{2,100}(?<!\S)", ""
$a = $a -replace " {", "{"
$a = $a -replace "} ", "}"
$a = $a -replace " \(", "\("
$a = $a -replace "\) ", "\)"
$a = $a -replace " \[", "\["
$a = $a -replace "\] ", "\]"
$a = $a -replace ": ", ":"
$a = $a -replace "; ", ";"
$a = $a -replace ", ", ","
$a = $a -replace "\n", ""
$a = $a -replace "\t", ""
# My version:
$b = gc d:\css\1.css -Raw
$b = $b -replace "\s{2,100}|[\n\t]", ""
$b = $b -replace '\s{0,1}([])}{([:;,])\s{0,1}', '$1'
# Test that they both do the same thing on my random downloaded sample file:
$b -eq $a
# Yep.
再次做到这一点与其他|
到两成一个组合:
$c = gc d:\css\1.css -Raw
$c = $c -replace "\s{2,100}|[\n\t]|\s{0,1}([])}{([:;,])\s{0,1}", '$1'
$c -eq $a # also same output as your original.
NB. that the space and tab and newline capture nothing, so '$1' is empty,
which removes them.
而且你可以花费大量的时间建立自己的不可读的正则表达式这可能不会明显快于任何实际场景。 :)
NB。 '$1'
在替换中,美元是.Net正则表达式引擎的语法,而不是PowerShell变量。如果你使用双引号,PowerShell将从变量$ 1中插入字符串,并且可能不会替换它。
我建议尝试使用字符串*方法*来替换字符串'$ a = $ a.replace(')','')'并测量时间。即使在大型文本中,如果结果比任何基于正则表达式的答案都快,也不要感到惊讶。无论如何,你应该使用适当的CSS解析。 – wOxxOm