I have an expression that follows some rules:
''
%
inside ''
''
Expression:
(?i)^(?<q>['])[%\p{Zs}\p{L}\p{N}|()]*\k<q>$
Now I need another expression to replace all ) and ( in a string for "TEST" for example, but only when they are not surrounded by ''. The trick is that when ) or ( are surrounded by '' but these characters belong to a different pair of '', it should not pass.
Example of results:
'(' > pass
' ( ' > pass
')' > pass
' ) ' > pass
' content here ' ' )' > pass
' content here' ) ' another content' > does not pass
Note that the first content has its '', and the second as well. Any ) or ( should not pass if its in between them.
I'm not a pro with regular expressions, so if you don't know how it would be, any documentation or tutorial related would be of great help.
I think this should do it:
Regex regex = new Regex(@"^'[^']*?'(?:(?:[^()]*)'[^']*?')*$");
Edit Demo
class Program
{
static void Main(string[] args)
{
Regex regex = new Regex(@"^'[^']*?'(?:(?:[^()]*)'[^']*?')*$");
string shouldPass1 = "'('";
string shouldPass2 = "' ( '";
string shouldPass3 = "')'";
string shouldPass4 = "'('";
string shouldPass5 = "' content here ' ' )'";
string shouldFail = "' content here' ) ' another content'";
Console.WriteLine("Pass1 : {0}",regex.IsMatch(shouldPass1));
Console.WriteLine("Pass2 : {0}", regex.IsMatch(shouldPass2));
Console.WriteLine("Pass3 : {0}", regex.IsMatch(shouldPass3));
Console.WriteLine("Pass4 : {0}", regex.IsMatch(shouldPass4));
Console.WriteLine("Pass5 : {0}", regex.IsMatch(shouldPass5));
Console.WriteLine("Fail : {0}", regex.IsMatch(shouldFail));
string wholeThing = string.Format(
"{0}\n{1}\n{2}\n{3}\n{4}\n{5}",
shouldPass1,
shouldPass2,
shouldPass3,
shouldPass4,
shouldPass5,
shouldFail);
Console.WriteLine("Alltogether (should fail too): {0}", regex.IsMatch(wholeThing));
}
}
Or without Regex (Tim Schmelter would be proud of me):
private static bool IsMatch(string text)
{
bool result = text[0] == '\'' && text[text.Length - 1] == '\'';
bool opened = false;
for (int i = 0; result && i < text.Length; i++)
{
char currentchar = text[i];
if (currentchar == '\'')
{
opened = !opened;
}
if (!opened && (currentchar == '(' || currentchar == ')'))
{
result = false;
}
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With