Click here to Skip to main content
15,893,668 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am retrieving details of drugs from an Array of strings.

The drugs name have company name attached to it which is a string.
ex-:BRUFEN[P&G].

I am trying to retrieve the Company name.
Basically the company name lies within the square braces as shown in example.

I tried using builtin string functions but not able to retrieve the company name from the given string.

Any help would be appreciated.

Thanks in Advance.
Posted
Updated 23-May-11 21:49pm
v3
Comments
Dalek Dave 24-May-11 3:49am    
Edited for Grammar and Readability.

If you want to use RegEx, simply go with
C#
string output=
Regex.Match(myString,@"(?<=\[).*(?=\])").Value;
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 24-May-11 2:05am    
Good, a 5. (By some reason I failed to do such a short Regex :-)
--SA
Abhinav S 24-May-11 2:05am    
Thank you SA.
Ashishmau 24-May-11 2:09am    
Perfect Solution
Abhinav S 24-May-11 3:57am    
Thanks for your opinion.
bsb25 24-May-11 2:16am    
5.
Why not just looking at the help page for System.String?

The trivial way is this:

C#
static string ExtractCompany(string source) {
   int bra = source.IndexOf('[');
   int ket = source.IndexOf(']');
   return source.Substring(bra, ket - bra - 1);
}


More sophisticated way would be using Regular Expression with the pattern "\[.*\]":

C#
using Regex = System.Text.RegularExpressions.Regex;

//...

static string ExtractCompany(string source) {
    string pattern = @"\[.*\]";
    Regex regex = new Regex(pattern);
    var matches = regex.Matches(source);
    if (matches.Count < 1) return; //for example
    return matches[0].Value.Trim(new char[] { '[', ']' });
}


—SA
 
Share this answer
 
Comments
[no name] 24-May-11 3:29am    
Good One SA. My 5 too.
Sergey Alexandrovich Kryukov 24-May-11 12:49pm    
Thank you, Ramalinga.
--SA
Kim Togo 24-May-11 5:38am    
My 5 for regular expressions.
Sergey Alexandrovich Kryukov 24-May-11 12:50pm    
Thank you, Kim.
--SA
Try following
s.Substring(s.IndexOf("[") + 1, s.IndexOf("]") - s.IndexOf("[") - 1)

where s is the drug's name.
 
Share this answer
 
v3
Comments
bsb25 24-May-11 1:55am    
works,thank u...5
Prerak Patel 24-May-11 1:56am    
You are welcome.
Sergey Alexandrovich Kryukov 24-May-11 2:04am    
Thank you for helping me, my solution was both substring and regex.
My 5 for yours.
--SA
Dalek Dave 24-May-11 3:50am    
Good Call.
This should work as well
public static string ExtractCompanyName(string data)
{
return(data.Substring(data.IndexOf("[")+1, data.Length-2 - data.IndexOf("[")));
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900