Replace string with unknown value

studio

#1

Hi,

I have a string for example “10 FOODS LESS 10% TAX”, and would like to replace “LESS 10% TAX” with “LESS TAX”. The problem is the 10% is supposed to be unknown.
Is there a way for me to replace “LESS * TAX” with “LESS TAX”?


#2

Hi,

Use substring like this

strInput.Substring(0, strInput.IndexOf(“Less”))

and with the output from it add the words “Less Tax”


#3

Hey @inyourgravity,
You can break it down into two strings and then concatinate in the third string.
assuming str contains “10 FOODS LESS 10% TAX”

index1=str.LastIndexOf(“S”)
index2=str.IndexOf(“T”)
str1=str.Substring(0,index1) //will give 10 FOODS LESS
str2=str.Substring(index2,str.Length) //will give TAX
str= str1+str2

str shall now become “10 FOODS LESS TAX”
Hope that helps :slight_smile:


#4

You can also use Regex.Replace()

You need to formulate a pattern to use first.
Since you want to replace the 10% you could easily just use a pattern like this:

"\s[0-9]{1,3}\%"

Then, use Regex.Replace()

System.Text.RegularExpressions.Regex.Replace(text, pattern, "")

So then only tricky part is finding the right patttern for you, which I will normally stick into a Message Box and test it with System.Text.RegularExpressions.Regex.Match(text, pattern).Value to see if it finds the right text.

Regards.


#6

Hi sorry I have not much experience with regex and am not back in office to test it yet.
But will the pattern remove the first ‘10’ before FOOD or will look for any number which ends ‘%’?


#7

Yeah, so basically [0-9] represents any integer from 0 to 9 and the {1,3} tells it that it’s 1 to 3 digits. Then, the \% is so it matches only if there’s a percent sign next to it.

It should look for the percentage regardless of what numbers if has.

Regards.