c# - 多个字符串在正则表达式中具有特殊字符

标签 c# regex

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 demoregex graph :

enter image description here

详细信息

  • / - 一个 / 字符
  • \.{1,2} - 1 或 2 个点
  • / - 一个 / 字符。

关于c# - 多个字符串在正则表达式中具有特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56698350/

相关文章:

c# - 如何确保异常 "The calling thread cannot access this object because a different thread owns it"?

c# - 您如何才能在 Xamarin.iOS UITableView 上仅圆化 2 个角?

c# - 连接字符串中缺少 MultipleActiveResultSets 导致错误

java - 使用java正则表达式时如何避免捕获重叠模式?

python - 如何在 re.sub 中增加 lambda 函数的值?

regex - ColdFusion 9 重新替换第 n 次出现的 HTML 标签

c# - 在 C# .NET 中将字符串格式化为固定长度

c# - Access 查询表达式中缺少运算符

javascript - 委内瑞拉电话号码的正则表达式与预期不匹配

regex - 为什么这个正则表达式即使没有问号也会匹配尽可能少的字符?