我需要能够检查带有|的模式 在他们中.例如,对于d*|*t像"dtest | test"这样的字符串,表达式应该返回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
Run Code Online (Sandbox Code Playgroud)
我有点选择,我应该怎么用?我的意思是这是一个非常基本的正则表达式我知道,但我不是因为某种原因得到它.
在正则表达式中,*意思是"零或更多(它之前的模式)",例如a*意味着零或更多a,并(xy)*期望形式的匹配xyxyxyxy....
要匹配任何字符,你应该使用.*,即
Regex Pattern = new Regex(@"s.*\|.*d");
Run Code Online (Sandbox Code Playgroud)
(另外,|意思是"或")
这里.将匹配任何字符[1],包括|.为避免这种情况,您需要使用字符类:
new Regex(@"s[^|]*\|[^d]*d");
Run Code Online (Sandbox Code Playgroud)
这里的[^x]意思是"任何字符除外x".
您可以阅读http://www.regular-expressions.info/tutorial.html以了解有关RegEx的更多信息.
[1]:除了新的一行\n.但如果您通过Singleline选项,.则会匹配\n.那么这是更高级的东西......
| 归档时间: |
|
| 查看次数: |
286 次 |
| 最近记录: |