I am trying to create a Regex expression to validate logical && || string combonation and its corresponding opening and closing () brackets.
I have been messing with the Regex hieroglyphic pattern but can’t seem to get it working correctly, mainly due to my complete lack of understanding of the Regex pattern.
After several hours of StackOverflow and google this is what I have so far, I feel I am close.
private void ValidationTest()
{
string hieroglyphics = @"^(?=^[^()]*\((?>[^()]+|\((?<DEPTH>)|\)(?<-DEPTH>))*(?(DEPTH)(?!))\)[^()]*$)[(]*\d+[)]*(\s+(&&|\|\|)\s+[(]*\d+[)]*)*$";
var tests = new List<string>
{
// Working
"(1 && 2)",
"((1 && 2) && (3 || 4))",
"((1 && 2) && (3 || 4) || ((1 && 2) && (3 || 4)))",
// Not working
"(Stack && Overflow)"
};
if (tests.All(test => Regex.IsMatch(test, hieroglyphics)))
{
MessageBox.Show("Woohoo!!");
}
}
So the main issue with what I have so far is if ther are no brackets 1 && 2 it wont validate, same with (1 && 2) && (3 || 4).
Also it seems to ignore words alltogeter (Stack && Overflow)
Examples of some strings I am tring to validate.
"IsRecording && IsPlaying"
"IsVisible && (IsPlaying && (IsMusic || IsRadio))"
There is also some keywords that contain brakets that could mess things up
Example:
"IsWindowVisible(2) && (IsControlVisible(22) && IsControlFocused(100))"
Edit:
As it is now this expression works fine validating the kind of complexity I need, however the only real issue I have is that its nubers only.
Complex example that validates fine with this Regex
"((1 && 2) && (3 || 4) || ((1 && 2) && (3 || 4)))"
A simple string 1 && 2 wont validate without brakets, but I dont mind adding brackest to these.
all I need is to add support for words instead of just numbers, this will be a fixed list of words if that helps.
If someone can spot the error or point me in a better direction would be awesome
Thanks
Edit:
Answer by mellamokb worked perfect. It seems the trouble was the d+ needed to be 0-9a-zA-Z()
Here is the pattern incase it usefull for anyone else.
string hieroglyphics = @"^(?=^[^()]*(?>[^()]+|\((?<DEPTH>)|\)(?<-DEPTH>))*(?(DEPTH)(?!))[^()]*$)[(]*[0-9a-zA-Z()]+[)]*(\s+(&&|\|\|)\s+[(]*[0-9a-zA-Z()]+[)]*)*$";
it validates exactly what I need
Examples:
"IsPlayer(Video) && Player(Playing)",
"((IsPlayer(Video) && (Player(Playing) && ControlIsVisible(34))) || (IsPlayer(Video) && (Player(Playing) && ControlIsVisible(34)))) && ControlIsFocused(22)"
I think the reason you are not able to validate expressions without a wrapping
()is the wrapping parentheses in your core nesting logic. If you take out the following parentheses I note below, then the other two non-wrapped expressions validate:Then in order to allow expressions that are not just numerical, you need to replace your restrictive
\dwith a more liberal definition of what you want to validate, say,[0-9a-zA-Z]:So it would become:
Demo: http://ideone.com/jwkcpL