Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, July 20, 2010 2:01 PM
Hi,
I've been tearing my hair out trying to do something very simple, replace a backslash character in a string with an underscore. I've searched online and discovered the -replace parameter which you would think would work fine but no, it seems to get in a tizzy because the character I want to replace is a backslash and I get an error: "Invalid regualr expression pattern".
Here's what I have which produces the error:
$str = 'start\end'
$str = $str -replace '\','_'
Can someone tell me how to do this? I simply want to replace a backslash with an underscore.
thanks
Jamie
http://sqlblog.com/blogs/jamie_thomson/ | @jamiet | About me
All replies (7)
Tuesday, July 20, 2010 2:05 PM ✅Answered | 2 votes
sod's law. I spend half an hour trying to figure this out and then as soon as I post this thread I figure it. The following works:
$str = 'start\end'
$str = $str -replace '\','_'
$str
http://sqlblog.com/blogs/jamie_thomson/ | @jamiet | About me
Tuesday, July 20, 2010 2:24 PM ✅Answered | 3 votes
sod's law. I spend half an hour trying to figure this out and then as soon as I post this thread I figure it. The following works:
$str = 'start\end'
$str = $str -replace '\','_'
$str
http://sqlblog.com/blogs/jamie_thomson/ | @jamiet | About me
"-replace" requires a regular expression for each argument, which is why you needed to escape your backslash with another backslash. If you use the replace() string method, you are not required to use regular expressions:
$str = $str.replace('\,'_') will work exactly as you expect it to.
Tuesday, July 20, 2010 2:34 PM
$str = $str.replace('\,'_') will work exactly as you expect it to.
Oh you're kidding me. That simple? Arrghhh!!!
I blame Google :)
http://sqlblog.com/blogs/jamie_thomson/ | @jamiet | About me
Tuesday, February 10, 2015 1:04 PM
Really fantastic . thank you very much
is this because with type first \ you can use then the character you need ??
Tuesday, February 10, 2015 1:34 PM | 1 vote
Really fantastic . thank you very much
is this because with type first \ you can use then the character you need ??
yes. backslash is what's known as an escape character.
Wednesday, February 11, 2015 11:26 PM
The backslash is an escap character, run that in Powershell and you will see it displays 2 backslahes :
[Regex]::Escape('\)
$str = [regex]::Replace($str, "\",',')
Friday, March 11, 2016 5:27 PM
Dear
I have the following:
$a="xx/xx"
I want to update $a in an SQL database as follows:
update table set field1=$a where field2='none'
But field1 should be written in the table as "xx/\xx"
I have no clue about haw to achieve this.
Thanks for the feedback
Peter
Peter Van Keymeulen, IT Infrastructure Solution Architect, www.edeconsulting.be