簡體   English   中英

正則表達式檢查某些字符

[英]Regular expression check for some characters

我想檢查字符串是否同時包含引號,例如''和括號(...),該字符串出現在字符串的任何位置。

例如

string s = "The flora and fauna of Britain \"has been transported to almost every corner of the globe since colonial times\" (Plants and Animals of Britain, 1942: 8).";

string x = "Morris et al (2000: 47) state 'that the debate of these particular issues should be left to representative committees.'";

我想出了這個:

Regex.IsMatch(x, @"(?<=""')[^\""]*(?=""')")

但是,我認為我會嘗試string。包含@RB提到的

@musefan,字符串s和y均為正結果,必須打開和關閉引號。

您可以使用Count方法使用LINQ來解決問題:

string s = "The flora and fauna of Britain \"has been transported to almost every corner of the globe since colonial times\" (Plants and Animals of Britain, 1942: 8).";

bool isMatch = s.Count(c => c == '"') % 2 == 0  ||
               s.Count(c => c == '\'') % 2 == 0 ||
               (s.Count(c => c == '(') == s.Count(c => c == ')'));

如果要確保字符串包含所有字符" ' ( )只需將||更改為&&

暫無
暫無

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

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