字符串变量作为Regex()构造函数中的模式

时间:2019-02-01 10:32:33

标签: c# regex visual-studio-2015

我不能在字符串变量中使用模式,因为正则表达式永远不匹配。

让我描述一下我想要实现的目标。我有一个返回密码字符串模式的服务。假设当前模式是:

\\b(?=.*?[A-Z])(?=.*?[0-9]).{6,}\\b

这意味着密码需要至少包含6个字符,一位数字和一个大写字母。我通过以下方式对其进行测试:

string passwordPattern = "\\b(?=.*?[A-Z])(?=.*?[0-9]).{6,}\\b";
var rgxPasswordPattern = new Regex(passwordPattern);
var result = rgxPasswordPattern.IsMatch("Password1");

if(result)
    Console.Write("Password match!");
else
    Console.Write("Password doesn't match!");

它有效,您可以在这里尝试:https://dotnetfiddle.net/FNzZjh

当我在环境中使用上述代码时,会发生问题。唯一的区别是我如何获得密码模式:

string passwordPattern = _signInService.GetPasswordPattern();

我注意到passwordPattern包含用引号引起来的模式: enter image description here

这会导致rgxPasswordPattern也包含带引号的标记: enter image description here

因此,我已将passwordPattern.Substring(1, passwordPattern.Length - 2)中的带引号的样式删除了:

enter image description here

并检查rgxPasswordPattern变量: enter image description here

是的,没有其他引号。但是密码仍然与模式不匹配! enter image description here

怎么可能?我不知道我还能做什么。模式很好,可以在 dotnetfiddle.net 中使用,但不能在我的环境中使用。

每一个建议我都会感激的。

1 个答案:

答案 0 :(得分:3)

此行

SELECT 
    MonthName [Month Name]
,   SUM(CASE WHEN MaterialName = 'M.Sand(Premium M sand concrete)' THEN Qty ELSE 0 END) [M.Sand(Premium M sand concrete)]
,   SUM(CASE WHEN MaterialName = 'M.Sand(Premium M sand Plaster -THRIVENI)' THEN Qty ELSE 0 END) [M.Sand(Premium M sand Plaster-THRIVEN)]
,   SUM(CASE WHEN MaterialName = '20MM' THEN Qty ELSE 0 END) [20MM]
-- ......... etc 
FROM (
    SELECT  
        DATENAME(MONTH,TripDate) [MonthName]
    ,   MM.MaterialName
    ,   SUM([NetWeight]) Qty 
    FROM 
        [TRANS].[tblWeighBridgeEntry] WB
    LEFT JOIN MAS.tblMaterialMaster MM ON MM.MaterialID = WB.RefMaterialId
    WHERE 
        TripDate  >=  DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(M, -6, CURRENT_TIMESTAMP)), 0) 
    GROUP BY 
        DATENAME(MONTH, TripDate)
    ,   MaterialName 
) D 
GROUP BY 
    MonthName

在C#中表示string passwordPattern = "\\b(?=.*?[A-Z])(?=.*?[0-9]).{6,}\\b"; 实际上包含以下字符串

passwordPattern

在C#中定义字符串时,反斜杠会转义以下字符。因此,如果要在字符串中添加\b(?=.*?[A-Z])(?=.*?[0-9]).{6,}\b //notice backslahes count 字符,则必须在\处加上双反斜杠。因此,您服务的问题在于它会在模式中返回额外的反斜杠。