How to use "Replace" only for the beginning or the end of the string?

I need to remove certain strings from a string, and I am thinking to use replace method. The problem is, this will replace a string with another, wherever it is found. For example,

string str = “123d456”
string result = str.Replace(“d”, “”)

The result will be “123456”, of course. How can I make this replace only for the beginning or the end of the string? For example,

string str = “d123d456”
string result = str.Replace(“d”, “”)

I want this result to be 123d456 instead of 123456. I want to only replace the string if it is at the beginning or the end of the string, and anything in the middle not to be affected by the method.

I don’t have to use replace method if there is a better way, but is there any way to do this?

1 Like

@tomato25

I think you need use if sentence to solve that.

strLen = str.length
If str.substring(0) = “d”
delete first “d”
if str.substring(strLen) = “d”
delete last “d”
else
do nothing.
end if

Rgds,
J,

.

1 Like

Hi @tomato25

Here is a sample code which use regex and replace activity in UiPath.

Please have a look and let me know it helps.

Regex Replace.zip (12.1 KB)

Cheers

1 Like

Hey @tomato25,

You can try something like this:

result=res1.ToCharArray()(0).ToString.Replace(“d”,“”) //For replacing the character from the beginnning.

result1=res1.ToCharArray()(result.length-1).ToString.Replace(“d”,“”)

1 Like

@tomato25 at that time you can go with substring buddy,like string.substring(1,7)
This will give you the output as 123d456

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.