I am new to Regular expression, I have a requirement to find "/./" or "/../" in a string. My program look likes as follow,
String Path1 = "https://18.56.199.56/Directory1/././Directory2/filename.txt";
String Path2 = https://18.56.199.56/Directory1/../../Directory2/filename.txt";
String Path3 = "https://18.56.199.56/Directory1/Directory2/filename.txt";
Regex nameRegex = new Regex(@"[/./]+[/../]");
bool b = nameRegex.IsMatch(OrginalURL);
此代码对于 Path3 也给出 true(没有任何“.”或“..”字符串)。
看起来表达式“Regex nameRegex = new Regex(@"[/./]+[/../]");”不是真的。请纠正这个表达。
正则表达式匹配 Path1 或 Path2 应该成功,而不是 Path3。
最佳答案
您的 [/./]+[/../]
(=[/.]+[/.]
) 正则表达式匹配 1+ /
或 .
字符后跟 /
或 .
。因此它可以匹配 ....../
、/////////////
,当然还有 //
> 在协议(protocol)部分。
如果您不必使用正则表达式,您可以简单地使用.Contains
:
if (s.Contains("/../") || s.Contains("/./")) { ... }
查看此C# demo .
您也可以使用以下正则表达式:
bool b = Regex.IsMatch(OrginalURL, @"/\.{1,2}/");
参见this regex demo和 regex graph :
详细信息
/
- 一个/
字符\.{1,2}
- 1 或 2 个点/
- 一个/
字符。
关于c# - 多个字符串在正则表达式中具有特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56698350/