سؤال

I have a list of string where one item is like, textItem1 = "Brown, Adam. (user)(admin)(Sales)" where I would always have to extract the text from the last pair of parentheses, which in this case will be Sales.

I tried the following:

string name = DDlistName.SelectedItem.ToString();
int start = name.IndexOf("(");
int end = name.IndexOf("(");
string result = name.Substring(start + 1, end - start - 1);
_UILabelPrintName.Text = result;

Problem: This always picks the text from first pair of parentheses, which in this case user.

Reading lots of similar question's answer I realised Regex might not be recommended in this case (not particularly succeeded either trying other codes). However any help with any short routine which can do the task will be really appreciated.

هل كانت مفيدة؟

المحلول

You need to use LastIndexOf instead of IndexOf, and check for a close parenthesis at the end.

string name = "Brown, Adam. (user)(admin)(Sales)";
int start = name.LastIndexOf("(");
int end = name.LastIndexOf(")");
string result = name.Substring(start + 1, end - start - 1);

Really you'd want to validate start and end to be sure that both parenthesis were found. LastIndexOf returns -1 if the character is not found.

And in order to handle nesting we need to search forward for the closing parenthesis after the location of the opening parenthesis.

 string name = "Brown, Adam. (user)(admin)((Sales))";
 int start = name.LastIndexOf('(');
 int end = (start >= 0) ? name.IndexOf(')', start) : -1;
 string result = (end >= 0) ? name.Substring(start + 1, end - start - 1) : "";

نصائح أخرى

You can use the split function, breaking the string at the opening parenthesis. The last array element is the desired output with a tailing ")", which will then be removed.

var input = "Brown, Adam. (user)(admin)(Sales)";
// var input = DDlistName.SelectedItem.ToString();

var lastPick = input.Split(new[] { "(" }, StringSplitOptions.RemoveEmptyEntries).Last(); 
var output = lastPick.Substring(0, lastPick.Length - 1);

_UILabelPrintName.Text = output;

Another approach is to use a while loop with IndexOf. It cuts the input string as long as another "(" is found. If not more "(" are found, it takes the contents of the remaining string until the closing parenthesis ")":

int current = -1;
while(name.IndexOf("(") > 0)
{
    name = name.Substring(name.IndexOf("(") + 1);
}

var end = name.IndexOf(")");
var output = name.Substring(0, end);

_UILabelPrintName.Text = output;

Or use LastIndexOf....

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top