【问题标题】:regex for specific URLField特定 URLField 的正则表达式
【发布时间】:2019-06-13 15:46:21
【问题描述】:

我正在尝试验证表单。 验证 url 字段时,我需要确保 用户提供没有 http(s):// 的字符串,但可以使用www. 以及xyz.abc.com 等字符串 - 请注意两个点。

我尝试过使用

UIApplication.sharedApplication().canOpenURL(url)

但这适用于我写了https://

我也从here尝试了这个正则表达式

    let regEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"

删除第一部分后,我似乎没有让多个点工作。

【问题讨论】:

  • 你想匹配像xyz.xyz.xyz.com这样的url还是最多2个点?检查这个regex101.com/r/8PLbeU/2这是你想要的吗?
  • @CodeManiac 谢谢,我正在尝试匹配用户希望的数量
  • 任何特定的域列表或任何随机的。评论链接是否符合您的目的或您有任何其他极端情况
  • @CodeManiac 不,这已经解决了。再次感谢

标签: ios swift regex


【解决方案1】:

你可以使用消极的lookbehind

let regEx = "(?<!((https|http)://))((\\w|-)+)(([.]|[/])((\\w|-)+))+"

所以给定这些字符串:

let string1 = "https://www.google.com"
let string2 = "stackoverflow.com/questions/54269877/regex-for-specific-urlfield"

用相同的谓词评估它们的结果:

let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[regEx])

会产生预期的结果:

predicate.evaluate(with: string1)  //false
predicate.evaluate(with: string2)  //true

【讨论】:

    猜你喜欢
    • 2013-12-29
    • 1970-01-01
    • 2012-05-06
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多