[英]Microsoft asp c# RegEx escape multiple reserved characters
我只想使用正則表達式,如果字符串中存在的字符不是可正常鍵入的字符,則它會返回true / false。 這應該是一件容易的事,不是嗎?
我本身沒有模式,我只想知道是否存在不在列表中的任何字符。
在常規RegEx世界中,我簡單地:
[^0-9a-zA-Z~`!@#$%\^ &*()_-+={\[}]|\\:;\"'<,>.?/] // <space> before the ampersand
我知道有點腫,但為這篇文章指出了重點
我發現您無法轉義多個保留字符。 例如,Regex ex = Regex.Escape(“ [”)+ Regex.Escape(“ ^”)不會命中:“ st [eve”或“ st ^ ve”
如以下失敗:
string ss = Regex.Escape("[") + Regex.Escape("^");
Regex rx = new Regex(ss);
string s = "st^eve";
rx.IsMatch(s));
以及以下任何一項:
string ss = Regex.Escape("[") + "[0-9]";
Regex rx = new Regex(ss);
string s1 = "st^eve"; rx.IsMatch(s1));
string s2 = "st^ev0e; rx.IsMatch(s2));
string s3 = "stev0e; rx.IsMatch(s3));
但這是不會失敗的Microsoft c#Regex轉義字符的唯一用法:
string ss = Regex.Escape("^");
Regex rx = new Regex(ss);
string s = "st^eve"; rx.IsMatch(s));
除非轉義字符測試外,是否還需要針對每個需要轉義的字符開發單獨的測試?
這是別人在做什么嗎?
如果有更好的方法,我願意提出意見。
感謝您的考慮。
考慮一下您作為表達式生成的內容。 您的示例RegEx
string ss = Regex.Escape("[") + Regex.Escape("^");
等效於:
string ss = @"\[\^";
也就是說,它不是在尋找[
或 ^
,而是在[
后跟 ^
。 所以ste[^ve
會匹配。
如果要匹配包含一個或多個字符的任何字符串,則需要添加(不轉義)方括號以創建一組字符,例如:
string ss = "[" + Regex.Escape("[") + Regex.Escape("^") + "]"
也就是說,您要讓Regex引擎在方括號內的一組字符中查找一個字符。
首先感謝@PMV。 他的輸入促使我進行了大量測試。
顯然,這是真正的工作方式。
不管我嘗試了什么,除非這兩個人分別進行測試,否則我無法獲得雙引號或單引號。 從頭到尾回想C語言,這實際上是有道理的。
注意:在任何情況下,你必須使用.Escape()
無論如何,IMO必須使用一個函數為您創建一個字符串=“ \\ [”只是愚蠢的。 .Escape() is not necessary on ^ nor { nor ] nor \\ nor " nor '
。
string ss = "[0-9A-Z~`!@#$%^& *()-_+={[}]|\\:;<,>.?/";
// does not match ~ ss = ss + Regex.Escape("\"");
// does not match ~ ss = ss + Regex.Escape("\'");
ss = ss + "]";
Regex rx = new Regex(ss);
// rx = new Regex("[" + Regex.Escape("\"") + "]");
// works just as well as the line above ~ rx = new Regex("[\"]");
// rx = new Regex("[" + Regex.Escape("'") + "]");
rx = new Regex("[']");
string s = "ste've";
Console.WriteLine("search string {0}", ss);
Console.WriteLine("IsMatch {0}", rx.IsMatch(s));
真是太棒了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.