簡體   English   中英

使用正則表達式檢測“ \\”(反斜杠)

[英]Detecting “\” (backslash) using Regex

我有一個C#正則表達式

[\"\'\\/]+

如果在字符串中找到某些特殊字符,我想用它來評估並返回錯誤。

我的測試字符串是:

\test

我有一個對此方法的調用來驗證字符串:

public static bool validateComments(string input, out string errorString)
{
    errorString = null;
    bool result;

    result = !Regex.IsMatch(input, "[\"\'\\/]+");  // result is true if no match
                                                   // return an error if match

    if (result == false)
        errorString = "Comments cannot contain quotes (double or single) or slashes.";

    return result;
}

但是,我無法匹配反斜杠。 我嘗試了幾種工具,例如regexpal和VS2012擴展,它們似乎都可以很好地匹配此regex,但是C#代碼本身不行。 我確實意識到C#會將字符串從Javascript Ajax調用傳入時轉義,所以還有另一種匹配該字符串的方法嗎?

它確實匹配/ test或'test或“ test,但不匹配\\ test

\\甚至被正則表達式使用。 嘗試"[\\"\\'\\\\\\\\/]+" (因此請對\\兩次轉義)

請注意,您可能有@"[""'\\\\/]+ ”,也許它會更易讀:-)(通過使用@ ,唯一必須轉義的字符是" ,通過使用第二個""

您實際上並不需要+ ,因為最后[...]意思是“其中之一”,對您來說就足夠了。

不要吃你無法咀嚼的東西...代替正則表達式使用

// result is true if no match
result = input.IndexOfAny(new[] { '"', '\'', '\\', '/' }) == -1;  

我認為沒有人會丟失工作,因為他更喜歡IndexOf而不是正則表達式:-)

您可以通過使字符串像這樣@逐字地解決此問題:

result = !Regex.IsMatch(input, @"[\""\'\\/]+");

由於反斜杠本身用作正則表達式內的轉義符,因此我發現在使用正則表達式庫時最好使用逐字字符串:

string input = @"\test";
bool result = !Regex.IsMatch(input, @"[""'\\]+");
//                                     ^^
// You need to double the double-quotes when working with verbatim strings;
// All other characters, including backslashes, remain unchanged.
if (!result) {
    Console.WriteLine("Comments cannot contain quotes (double or single) or slashes.");
}

唯一的問題是您必須將雙引號加倍(具有諷刺意味的是,這是您需要做的事情)。

ideone演示

對於平凡的情況,我可以使用regexhero.net使用以下簡單的測試表達式:

\\

驗證

\test

RegExHero生成的代碼:

string strRegex = @"\\";

RegexOptions myRegexOptions = RegexOptions.IgnoreCase;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"\test";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    // Add your code here
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM