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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With