【问题标题】:How to test string with regular expression in C#?如何在 C# 中使用正则表达式测试字符串?
【发布时间】:2011-05-14 07:29:47
【问题描述】:

我有 URL 链接,例如“images.myweb.com/files”或“test.com/images”
我想检查 URL 是否包含像
".com/" or ".in/" or ".net/" or ".org/" 的正则表达式。

如何使用 C# 正则表达式..

【问题讨论】:

  • 那么,你想要一个正则表达式,即使它不是最适合这项工作的东西?最好问什么是实现你需要的最佳方式,而不是告诉人们如何去做。

标签: c# regex


【解决方案1】:

不要使用正则表达式,只需使用 URI 类和 String.EndsWith()

Uri baseUri = new Uri("http://www.contoso.com:8080/images");
  bool isCom = baseUri.Host.EndsWith(".com");
  bool isNet= baseUri.Host.EndsWith(".net");
  bool isOrg = baseUri.Host.EndsWith(".org");

也许结合String.ToLower() 来绕过区分大小写。

【讨论】:

  • 使用您的示例,www.computer.nl 会发生什么?
【解决方案2】:

lst 是您的字符串列表(如lst = new []{".com/" , ".in/" ,".net/" ,".org/"}),那么您可以使用 Linq 来完成:

lst.Any(x=>myString.Contains(x))

如果你想让你的字符串以这个项目结尾:

lst.Any(x=>myString.EndsWith(x))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多