How to remove anything in a string after last number

Dear all

I have the following string: voltaren 50 mg 20 tablet. I would like to find the last number, in this case 20, and remove everything after:

voltaren 50 mg 20

then I want to remove this number:

voltaren 50 mg

And then I want to again remove anything after the last number:

voltaren 50

How can I do it with regex?

Thanks a lot
G.

what you at the end

Hi @Gennaro_Bozza,

Use replace activity
You can use regex to replace the end of the string

Pattern: \w+$

Regards,
Arivu

1 Like

Hi @arivu96

Thanks for your reply! Can you write the regex expressions for the 3 steps of my example so that I understand better?
Thanks
Gennaro

You want regex only or split function would be ok ?

Hi @Gennaro_Bozza,

What is your expected output from your input, so I can give the correct answer.

Regards,
Arivu

Hi @Gennaro_Bozza

You may use
string valuesReq = Regex.Split(x, @"\D+\d+");
Out put will be a array that contains some empity string and last value of your string ,in your case “tablet”.To aviod empty space use if condition !string.IsNullOrEmpty in loop.

And if you to get all string values splited on the bases of numbers then use
string valuesReq = Regex.Split(x, @"\d+");
it will reurn an array that contain values voltaren,mg and tablet

And to get only numbers from you string use
string valuesReq = Regex.Split(x, @"\D+");
It will retrun number present in your string, using those you can get indiex and use split after that,

And to remove last string use
string valuesReq = Regex.Split(x.Trim(), @"\D+$");
Output : “voltaren 50 mg 20”

Hi @arivu96

thanks for your reply!
Input: voltaren 50 mg 20 tablet.
1st Output: remove all words after last number: voltaren 50 mg 20
2nd Input: voltaren 50 mg 20
2nd Output: remove this last number: voltaren 50 mg
3rd input: voltaren 50 mg
3rd Output: same as step 1, remove all words after last number: voltaren 50

Many thanks
G.

Hi @Rashmi,

also split is ok. Up to now no one managed to figure out the solution. Any help appreciated!
G.

Hi Gagaru,
thanks for your help but I don’t Need the last value of my string, I need anything after the last number, which makes it more tricky. So far no one managed to find the solution.
Furthermore, the output needs to be a string and not an array.
Thanks
G.

Solution found:
System.Text.RegularExpressions.Regex.Replace(ProductDescription,"[^(\d+)(?!.*\d)]*$","") Returns voltaren 50 mg 20

System.Text.RegularExpressions.Regex.Replace(System.Text.RegularExpressions.Regex.Replace(ProductDescription,"(\d+)(?!.*\d).*$",""),"\s+$","") Returns voltaren 50 mg

System.Text.RegularExpressions.Regex.Replace(System.Text.RegularExpressions.Regex.Replace(ProductDescription,"(\d+)(?!.*\d).*$",""),"[^(\d+)(?!.*\d)]*$","") returns voltaren 50