-2

正则表达式在双引号之间获取文本表单字符串,其中至少包含任何一个

:=, &&, ||, ==, <, >, <=, >=, <>, &, +, -, *, /, ? .

代码:

 script = "if(a<=b, strcat(\" userid <= 'tom' \",\" and test = 1\", \" and test >= 10 \"), nop());";
string tempScript = (script ?? "").Trim();

var functionMatches = Regex.Matches(tempScript, @"Some RegEx");
if (functionMatches != null && functionMatches.Count > 0)
{
    foreach (Match fm in functionMatches)
    {
        Console.WriteLine(fm.Value);
    }
}

Console.ReadLine();

例如:

Input :- 
    "if(a<=b, strcat(" userid <= 'tom' "," and test = 1", " and test >= 10 "), nop());"

Output :-

    1) " userid <= 'tom' "

    2) " and test >= 10 "

谢谢。

4

1 回答 1

3

其实好像没那么简单……

我建议首先查找双引号"..."之间的所有字符串,然后检查每个字符串是否包含您提供的特殊字符。所以它会是这样的:

正则表达式

  • (?<=\")[^,]+?(?=\")
  • ^.+?(<=|>=|<>|\|\||:=|&&|==|<|>|&|\+|-|\*|/|\?).+?$

    代码:

    string pattern = "(?<=\")[^,]+?(?=\")";
    string patternSpecial = @"^.+?(<=|>=|<>|\|\||:=|&&|==|<|>|&|\+|-|\*|/|\?).+?$";
    string input = "if(a<=b, strcat(\" userid <= 'tom' \",\" and test = 1\", \" and test >= 10 \"), nop());";  
    
    foreach (Match m in Regex.Matches(input, pattern))
    {
        if (Regex.IsMatch(m.Value, patternSpecial))
        {
            Console.WriteLine(Regex.Match(m.Value, patternSpecial).Value);
        }
    }
    
    Console.ReadLine();
    

    输出:

    用户 ID <= '汤姆'

    并测试 >= 10


    仅使用一种模式和更少的 C# 代码:

    正则表达式

    \"([^"]+?(<=|>=|<>|\|\||:=|&&|==|<|>|&|\+|-|\*|/|\?).+?)\"
    

    代码:

    string pattern = "\"([^\"]"+@"+?(<=|>=|<>|\|\||:=|&&|==|<|>|&|\+|-|\*|/|\?).+?)"+"\"";
    string input = "if(a<=b, strcat(\" userid <= 'tom' \",\" and test = 1\", \" and test >= 10 \"), nop());";  
    
    foreach (Match m in Regex.Matches(input, pattern))
    {
        Console.WriteLine(m.Groups[1]);
    }
    
    Console.ReadLine();
    

    输出:

    用户 ID <= '汤姆'

    并测试 >= 10

  • 于 2013-11-09T11:21:12.483 回答