Reputation: 345
i have a text pattern like this;
(((a) or (b) or (c)) and ((d) or (e)) and ((!f) or (!g)))
and i want to get it like this;
((a) or (b) or (c))
((d) or (e))
((!f) or (!g))
After that i want to seperate them like this;
a,b,c
d,e
!f,!g
any help would be awesome :)
edit 1: sorry about the missing parts; using language is C# and this is what i got;
(\([^\(\)]+\))|([^\(\)]+)
with i got;
(a) or (b) or (c) and (d) or (e) and (!f) or (!g)
thanks already!
Upvotes: 2
Views: 281
Reputation: 345
After my work i figure this;
string msg = "(((a) or (b) or (c)) and ((d) or (e)) and ((!f) or (!g)))";
Regex regex = null;
MatchCollection matchCollection = null;
regex = new Regex(@"(\([^\(\)]+\))|([^\(\)]+)"); // For outer parantheses
matchCollection = regex.Matches(query);
foreach (Match match in matchCollection)
{
MatchCollection subMatchCollection = Regex.Matches(match.Value, @"(""[^""]+"")|([^\s\(\)]+)"); // For value of inner parantheses
foreach (Match subMatch in subMatchCollection)
{
//with 2 loops i got each elements of this type of string.
}
}
Thanks to everyone! :)
Upvotes: 0
Reputation: 71538
Taking this previous regex and modifying the code a little...
string msg= "(((a) or (b) or (c)) and ((d) or (e)) and ((!f) or (!g)))";
var charSetOccurences = new Regex(@"\(((?:[^()]|(?<o>\()|(?<-o>\)))+(?(o)(?!)))\)");
var charSetMatches = charSetOccurences.Matches(msg);
foreach (Match mainMatch in charSetMatches)
{
var sets = charSetOccurences.Matches(mainMatch.Groups[1].Value);
foreach (Match match in sets)
{
Console.WriteLine(match.Groups[0].Value);
}
}
The first regex is being used to get the contents of the outermost paren.
The same regex is then used to get the individual sets within the 'larger' content. You get this as output:
((a) or (b) or (c))
((d) or (e))
((!f) or (!g))
If you want to remove the outer parens, just change the innermost line:
Console.WriteLine(match.Groups[0].Value);
to
Console.WriteLine(match.Groups[1].Value);
To get:
(a) or (b) or (c)
(d) or (e)
(!f) or (!g)
I trust you can take it from here.
Upvotes: 1