0

I am starting from this example in JavaScript, and trying to do the same performance test.

I have

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$RegEx1 = '/ +/g'
$RegEx2 = '/  +/g'
$RegEx3 = '/ {2,}/g'
$RegEx4 = '/\s\s+/g'
$RegEx5 = '/ +(?= )/g'


Measure-Command {
    $newString = $string -replace $RegEx1, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx2, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx3, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx4, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx5, $null
}
Write-Host "$newString"

and I am getting very different times, but all return nothing, which isn't exactly useful. Where am I going wrong translating Javascript RegEx to PowerShell Regex? FWIW, I want to keep things simple, so spaces only, no need to also replace CR and the like. The data is pretty simple, the formatting is just junk.

Community
  • 1
  • 1
Gordon
  • 6,257
  • 6
  • 36
  • 89

1 Answers1

1

In PowerShell (by extension I think .Net in general) your modifiers/options are supposed to be at the beginning of the string in a construct like (?smi)/ + for example.

Replace white space with a single space

$newString = $string -replace "\s+", " "

That should do it just fine if you want simplicity.

Consider this example using your regex string to show what you would be trying to match against.

"this is only a /    /g" -replace '/ +/g', "test"
this is only a test

A pair of literal forward slashes with at least one space separating them followed by the literal g.

Matt
  • 45,022
  • 8
  • 78
  • 119
  • So, seeing it makes sense, but growing the problem wasn't going to happen. RegEx messes with my head. Thanks! Now on to the next RegEx question of the day. – Gordon Mar 31 '17 at 16:22