Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing 3 specific characters, if present from the start of a string VB.net

I have a situation where I need remove a prefix from a string, if it exists.

Dim str As String = "samVariable"

Needs to be converted to Variable

Easy, with TrimStart

str = str.trimstart("s"c, "a"c, "m"c)

Except...

The string might not always start with "sam"

Example:

Dim str As String = "saleDetails"

This will now become aleDetails

Which is wrong, so how about Replace

str = str.Replace('sam','')

Brilliant! Now:

Example 1:

Dim str As String = "samVariable"
str = str.Replace('sam','')
str = "Variable"

Example 2:

Dim str As String = "saleDetails"
str = str.Replace('sam','')
str = "saleDetails" (unaffected)

BUT....

What if:

Dim str As String = "Resample"
str = str.Replace('sam','')
str = "Reple"

This is wrong again!

So, my question is:

How do I remove "sam" from the beginning of a string only?

I had expected TrimStart("sam") to work, but it doesn't

like image 736
Jamie Hartnoll Avatar asked Dec 10 '25 21:12

Jamie Hartnoll


1 Answers

str = New Regex("^sam").Replace(str, String.Empty)

The regular expression looks for sam at the start of the string and replaces it with empty, effectively removing the sam from the beginning.

EDIT Per Konrad's comment, the shared method call would be better:

str = Regex.Replace(str, "^sam", String.Empty)
like image 88
Joe Enos Avatar answered Dec 13 '25 11:12

Joe Enos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!