view raw
sforsandeep sforsandeep - 10 months ago 27 Question

Replace a specific pattern of text in a string with a character

I've a string like this

Always $1| Sometimes $27| Never $33|No Answer$0

I need to replace all occurance of this pattern
$ + number + |
with comma

So the resulting string should be like

Always, Sometimes,Never,No Answer

So How can I use replace function for this purpose

I tried using

Dim myText as strin ="Always $1| Sometimes $27| Never $33|No Answer$0"
Regex.Replace(mytext, "\$(.+?)\|", ",")

But the last $ and number keeps there. So am getting something like this

Always,Sometimes,Never,No Answer$0

But I need to remove the ending $0 too

So the final result should be

Always,Sometimes,Never,No Answer


You can use the question mark to allow for optional characters to match (the pipe character, but also spaces if that was necessary). Does something like this work for you?

Dim str As String = "Always $1| Sometimes $27| Never $33|No Answer$0"
str = Regex.Replace(str, "\s?\$\d+\|?\s?", ",").TrimEnd({","c, " "c})


Always,Sometimes,Never,No Answer