Remove the text after second occurance

Hi,

I want to remove the text from a string if the string consists of (). The text in between () has to be removed. I have seen some examples from the forum where

Text = 7744-Head of Credit(GM) (IT PLANNING DEPT. (LN))

Text.Split("("c)(0).ToString.Trim

Output will be 7744-Head of Credit

but if I have some examples as below

E.g: → 7744-Head of Credit(GM) (IT PLANNING DEPT. (LN))
→ 9999-Assistant CO (Placeholder Dept Code)

I need to get the output as

7744-Head of Credit(GM)
9999-Assistant CO

Is it possible or not if yes please help me.

Use System.Text.RegularExpressions.Regex.Replace(Text, "\(.*\)", "()") for each line of the text. This will leave only the () which was surrounding the text. If you want to remove that as well, use System.Text.RegularExpressions.Regex.Replace(Text, "\(.*\)", String.Empty).

Hi,
Thanks for the reply but I am getting a different output.

I need to remove the text “(IT PLANNING DEPT. (LN))” from the 7744-Head of Credit(GM) (IT PLANNING DEPT. (LN))

My output should be “7744-Head of Credit(GM)”

In string manipulation, to find the position of a certain char, we use IndexOf function, in your case to find the second occurrence you should do the same two time, see the below function to give you an idea:

int IndexOfSecond(string theString, string toFind)
{
int first = theString.IndexOf(toFind);

if (first == -1) return -1;

// Find the "next" occurrence by starting just past the first
return theString.IndexOf(toFind, first + 1);

}

After you get the position of the second time the ( appears, you can use the Substring method like this:
myResult = OriginalText.Substring(0, indexOfecond)

Would this work then? The regular expression below removes everything after the first right parentheses.

System.Text.RegularExpressions.Regex.Replace(Text, "\).*", ")")

1 Like

Hi Anthony,

It is working for some of the example but can we remove the text after second ( parenthesis.

For example we have text_(someone_1) (someone_2)
output has to be only text_(someone_1)

The regex I’ve provided above works for the example you’ve given.