-1

I'm trying the following...

$string = "*abc*"
$string = $string -replace "*",""
Write-Host $string

but get the following error

Regular expression pattern is not valid: *.
At C:\Scripts\Tests\testing.ps1:3 char:1
+ $string = $string -replace "*",""
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (*:String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression

I've tried -replace, .replace, .trim, but none of them are working because they are all reading it as a regular expression. I've also tried "`*", and it still doesn't work.

Anyone know how to make the system not to read as a regex?

Ansgar Wiechers
  • 175,025
  • 22
  • 204
  • 278
Fiddle Freak
  • 1,347
  • 1
  • 23
  • 56
  • Possible duplicate of [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Matt Dec 22 '15 at 17:53

4 Answers4

2

Try using \ to escape it instead of the backtick.

Nate
  • 680
  • 5
  • 25
  • It's confirmed this also works, however backslashes are risky since the regex for removing whitespaces are `\s`. I think the square brackets are the safer bet. I'll still mark your answer is being correct though. – Fiddle Freak Dec 22 '15 at 17:33
1

Could you try this ?

$string = $string.replace('*','')

Hope it will work !

Vince G
  • 328
  • 1
  • 4
  • 20
1

You can use square brackets to remove the characters.

$string = $string -replace '[*]', ''
dfundako
  • 7,178
  • 3
  • 14
  • 30
  • Thanks this is working. Using the `\*` also worked, but I noticed a bug if the string involves spaces. I think your way is much better. Thanks again :) – Fiddle Freak Dec 22 '15 at 17:23
0

If you don't want the system to use regex then you should not be using a regex operator like -replace. The string method .Replace() would work just as fine. You said .Trim() did not work either but indeed it does. Possibly and issue with your real data as supposed to your example in the question.

PS C:\temp> "'{0}'" -f "*abc*".replace("*","")
'abc'

PS C:\temp> "'{0}'" -f "*abc*".Trim("* ")
'abc'

PS C:\temp> "'{0}'" -f "*  abc* ".Trim("* ")
'abc'
Matt
  • 40,384
  • 7
  • 62
  • 97