TTomu
TTomu

Reputation: 99

regex split and filter construction

I need to filter input, to get only string inside parenthesis: Test1, Test2, Test3. I have try, but it is not working.

 string input = "test test test @T(Test1)  sample text @T(Test2) Something else @T(Test3) ";
 string pattern = @"[@]";
 string[] substrings = Regex.Split(input, pattern);

Upvotes: 2

Views: 184

Answers (2)

vks
vks

Reputation: 67968

You can use a simple match instead.

(?<=@T\().*?(?=\))

string strRegex = @"(?<=@T\().*?(?=\))";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"test test test @T(Test1)  sample text @T(Test2) Something else @T(Test3) ";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
   if (myMatch.Success)
   {
    // Add your code here
  }
}

Upvotes: 4

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626803

Note that @"[@]" regex pattern matches a single @ character anywhere inside an input string. When you split against it, you are bound to get more than you need.

You should be matching rather than splitting:

string input = "test test test @T(Test1)  sample text @T(Test2) Something else @T(Test3) ";
string pattern = @"@T\((?<val>[^()]*)\)";
string[] substrings = Regex.Matches(input, pattern)
           .Cast<Match>()
           .Select(p => p.Groups["val"].Value)
           .ToArray();

enter image description here

The @T\((?<val>[^()]*)\) regex will match:

  • @T - literal @T
  • \( - a literal (
  • (?<val>[^()]*) - (Group with "val" name) 0 or more characters other than ( or )
  • \) - a literal )

Upvotes: 3

Related Questions