BattlFrog
BattlFrog

Reputation: 3397

Find all characters between the parenthesis

I have a list of mutual funds that I need to pull the ticker symbols out of. The list is like this:

FID SEL TELECOMM (FSTCX)07/29/1985
FID SEL UTILITIES (FSUTX)12/10/1981
SPTN REAL ES IDX ADV (FSRVX)09/08/2011
SA EMERGING MKTS FOF (FLILX)05/02/2012
SA INTL MULTI MGR (FMJDX)05/02/2012
FID ASSET MGR 85% (FAMRX)09/24/1999

I need to pull the 5 characters from each line that are sitting in the parens (). I am then going to write to a new file, but for now I can't seem to return just the ticker (chars between the parens). I should get:

FSTCX
FSUTX
FSRVX
FLILX
FMJDX
FAMRX

Instead, it returns the entire line. Here's what I have (in C#).

Regex pattern = new Regex(@"\(([A-Z]*)\)");

StreamReader reader = new StreamReader("C:\\MyDocuments\\TickerList.txt");

string line;

while ((line = reader.ReadLine()) != null)                
{
    Match match = pattern.Match(line);

    if (match.Success)
    {
        Console.WriteLine(line);
        Console.ReadLine();
    }
}

Upvotes: 0

Views: 68

Answers (4)

Ry-
Ry-

Reputation: 224904

Console.WriteLine(line); does not involve match.

if (match.Success)
{
    Console.WriteLine(match.Groups[1].Value);
    Console.ReadLine();
}

And you can use File.ReadLines, too:

Regex pattern = new Regex(@"\(([A-Z]*)\)");

for (var line in File.ReadLines(@"C:\MyDocuments\TickerList.txt")) {
    Match match = pattern.Match(line);

    if (match.Success) {
        Console.WriteLine(match.Groups[1].Value);
        Console.ReadLine();
    }
}

Or maybe…

File.ReadLines(@"C:\MyDocuments\TickerList.txt")
    .Select(pattern.Match)
    .Where(m => m.Success)
    .Select(m => m.Groups[1].Value)

(maybe)

Upvotes: 2

L.B
L.B

Reputation: 116108

Regex + Linq

string input = File.ReadAllText("C:\\MyDocuments\\TickerList.txt");

var values = Regex.Matches(input, @"\((.+?)\)").Cast<Match>()
                .Select(m => m.Groups[1].Value)
                .ToList();

Upvotes: 2

Braj
Braj

Reputation: 46841

Try below regex and get matched group.

\((\w+)\)

DEMO

String literals for use in programs: @"\((\w+)\)" for c#

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

Your regex would be,

Regex pattern = new Regex(@"\(([^\)]*)\)");

DEMO

And don't forget to print the matched group 1.

Upvotes: 1

Related Questions