Here is an example program written in C# - the comments describes what was changed during the feedback from the comments, and the regex's are in the order they appeared in this post.
// Porgram has been modifed in accordance with the dabate in the comments section
using System;
using System.Text.RegularExpressions;
namespace CS_Regex
{
class Program
{
// Match parenthesized texts that aren't followed by a question mark.
static void Main(string[] args)
{
string[] tests =
{
"(match this text) ignore this (ignore this)? and (match this) (and this)"
};
// The first three patterns matches, if the left parenthesis is not the last character.
// The last pattern matches all parenthesized texts.
string[] patterns = {
@"\((.*?)\)[^?]", // Original regex
@"\((.*)\)[^?]", // Regex that matches greedily, which was my first example, that caused the discussion in the comments.
// I asked "Why do you have a question mark after matching zero or more characters?"
@"(\([^)]*\))[^?]", // Regex that only matches if the left parenthesis is followed by another character, avoiding the use of the '?' operator.
@"(\([^)]*\))(?!\?)", // Regex that matches all instances
};
foreach (string pattern in patterns) {
Regex rx = new Regex(pattern, RegexOptions.Compiled);
Console.WriteLine($"Regex: {pattern}");
foreach (string data in tests)
{
MatchCollection matches = rx.Matches(data);
Console.WriteLine($"{matches.Count} matches found in: {data}");
foreach (Match match in matches)
Console.WriteLine($" matched value and group: '{match.Value}' and '{match.Groups[1]}'");
}
}
Console.ReadKey();
}
}
}
The program produces the following output:
Regex: \((.*?)\)[^?]
2 matches found in: (match this text) ignore this (ignore this)? and (match this) (and this)
matched value and group: '(match this text) ' and 'match this text'
matched value and group: '(ignore this)? and (match this) ' and 'ignore this)? and (match this'
Regex: \((.*)\)[^?]
1 matches found in: (match this text) ignore this (ignore this)? and (match this) (and this)
matched value and group: '(match this text) ignore this (ignore this)? and (match this) ' and 'match this text) ignore this (ignore this)? and (match this'
Regex: (\([^)]*\))[^?]
2 matches found in: (match this text) ignore this (ignore this)? and (match this) (and this)
matched value and group: '(match this text) ' and '(match this text)'
matched value and group: '(match this) ' and '(match this)'
Regex: (\([^)]*\))(?!\?)
3 matches found in: (match this text) ignore this (ignore this)? and (match this) (and this)
matched value and group: '(match this text)' and '(match this text)'
matched value and group: '(match this)' and '(match this)'
matched value and group: '(and this)' and '(and this)'
The example has been edited, to reflect the discussion in the comments.