[英]How would that regular expression be?
我有一个遵循一些规则的表达式:
''
内部可能有零个或多个空格 %
''
''
里面可以有零个或多个单词(字母和数字) 表达:
(?i)^(?<q>['])[%\p{Zs}\p{L}\p{N}|()]*\k<q>$
现在我需要另一个表达式来替换所有)和(例如,在“TEST”的字符串中,但仅当它们没有被''包围时。诀窍是当时)或(被''包围但是这些字符属于一对不同的'',它不应该通过。
结果示例:
'(' > pass
' ( ' > pass
')' > pass
' ) ' > pass
' content here ' ' )' > pass
' content here' ) ' another content' > does not pass
请注意,第一个内容有'',第二个内容也有。 任何)或(如果它介于它们之间,则不应通过)。
我不是正则表达式的专业人士,所以如果你不知道它是怎么回事,任何相关的文档或教程都会有很大的帮助。
你可以使用正则表达式:
^.*[()](?=[^']*'(?>(?:[^']*'[^']*){2})*$)
见演示 。
码:
var rgxHardNut = new Regex(@"^.*[()](?=[^']*'(?>(?:[^']*'[^']*){2})*$)");
var check1 = rgxHardNut.IsMatch("'('"); // true
var check2 = rgxHardNut.IsMatch("' ( '");// true
var check3 = rgxHardNut.IsMatch("')'"); // true
var check4 = rgxHardNut.IsMatch("' ) '");// true
var check5 = rgxHardNut.IsMatch("' content here ' ' )'"); // true
var check6 = rgxHardNut.IsMatch("' content here' ) ' another content'"); // false
我认为应该这样做:
Regex regex = new Regex(@"^'[^']*?'(?:(?:[^()]*)'[^']*?')*$");
编辑演示
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));
}
}
或者没有正则表达式( Tim Schmelter会为我感到骄傲):
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.