[英]Regular expression with “|”
我需要能夠使用|檢查模式。 在他們中。 例如,對於類似“ dtest | test”的字符串,類似d*|*t
的表達式應返回true。
我不是正則表達式英雄,所以我嘗試了幾件事,例如:
Regex Pattern = new Regex("s*\|*d"); //unable to build because of single backslash
Regex Pattern = new Regex("s*|*d"); //argument exception error
Regex Pattern = new Regex(@"s*\|*d"); //returns true when I use "dtest" as input, so incorrect
Regex Pattern = new Regex(@"s*|*d"); //argument exception error
Regex Pattern = new Regex("s*\\|*d"); //returns true when I use "dtest" as input, so incorrect
Regex Pattern = new Regex("s*" + "\\|" + "*d"); //returns true when I use "dtest" as input, so incorrect
Regex Pattern = new Regex(@"s*\\|*d"); //argument exception error
我的選項有點用完了,那我應該怎么用? 我的意思是我知道這是一個非常基本的正則表達式,但是由於某種原因我沒有得到它。
在正則表達式中, *
表示“零或多個(之前的模式)”,例如a*
表示零或多個a
,並且(xy)*
期望形式為xyxyxyxy...
匹配項。
要匹配任何字符,應使用.*
,即
Regex Pattern = new Regex(@"s.*\|.*d");
(此外, |
表示“或”)
在這里.
將匹配任何字符[1] ,包括|
。 為了避免這種情況,您需要使用一個字符類 :
new Regex(@"s[^|]*\|[^d]*d");
這里[^x]
表示“除x
之外的任何字符”。
您可以閱讀http://www.regular-expressions.info/tutorial.html來了解有關RegEx的更多信息。
[1]:除了換行\\n
。 但是.
如果通過“單行”選項,則將匹配\\n
。 好吧,這是更高級的東西...
A |
在char class
將按字面意義對待,因此您可以嘗試regex:
[|]
在Javascript中,如果您構造
var regex = /somestuff\\otherstuff/;
,
然后反斜杠就如您所願。 但是,如果您使用不同的語法構造相同的東西
var regex = new Regex("somestuff\\\\otherstuff");
那么由於解析Javascript的方式很怪異,您必須將所有反斜杠加倍 。 我懷疑您的第一次嘗試是正確的,但是您在解決舊問題的同時又引入了一個新問題,因為您遇到了與另一個反斜杠有關的其他問題。
s.*\\|.*d
怎么樣?
嘗試的問題是,您編寫了類似s*
東西-這意味着:匹配任意數量的s
(包括0)。 您需要使用來定義s之后的字符.
就像我的例子一樣 您只能將\\w
用作字母數字字符。
嘗試這個。
string test1 = "dtest|test";
string test2 = "apple|orange";
string pattern = @"d.*?\|.*?t";
Console.WriteLine(Regex.IsMatch(test1, pattern));
Console.WriteLine(Regex.IsMatch(test2, pattern));
Regex Pattern = new Regex(@"s*\\|*d");
將有效,除了||表示“ 0個或更多管道”。 因此,您可能希望Regex Pattern = new Regex(@"s.*\\|.*d");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.