【问题标题】:The operation couldn’t be completed. (Cocoa error 2048.)操作无法完成。 (可可错误 2048。)
【发布时间】:2016-02-26 13:37:25
【问题描述】:

我对使用正则表达式有点陌生。 我收到以下错误:

操作无法完成。 (可可错误 2048。)

当尝试在 Swift 中使用 NSRegularExpression 构建以下正则表达式时:

let regex = try NSRegularExpression(pattern: "^(?=.*[A-Z])(?=.*[a-z]).{7-15}$", options: .CaseInsensitive)

我正在尝试验证用户输入字符串是否包含至少一个大写字母和至少一个小写字母,同时将字符串的长度限制在 7 到 15 个字符之间。谢谢

【问题讨论】:

  • 我认为应该改变两件事:1)将限制量词从{7-15}修复为{7,15},2)删除.CaseInsensitive标志,替换为[]。 (如果不接受[],请尝试nil)。
  • 谢谢,我明白你的意思了,我用 [ ] 替换了 .CaseInsensitive 标志。

标签: regex swift cocoa


【解决方案1】:

您的模式并不完全正确。长度范围语法使用逗号:

"^(?=.*[A-Z])(?=.*[a-z]).{7,15}$"

【讨论】:

  • happens:) 如果您批准答案会很好,除非您想一起摆脱这个问题
  • 如果你把它和options: .CaseInsensitive一起使用,像abcdefgh这样的字符串也会通过。
【解决方案2】:

为了验证用户输入,使用这个正则表达式:

^(?=.*[a-z])(?=.*[A-Z])(?=.{7})(?!.{16}).+$

^               // start of the string
(?=.*[a-z])     // assert that at least one lowercase exists
(?=.*[A-Z])     // assert that at least one uppercase exists
(?=.{7})        // assert that at least 7 characters exists
(?!.{16})       // assert that the string cannot exceed 15 characters (negative lookahead)
.+              // get the entire string
$               // end of the string

您可以查看the demo here

【讨论】:

  • 那个链接太棒了。谢谢。
  • @Maria1985 我很高兴它可以提供帮助。如果它对您有用,请不要忘记投票。将不胜感激。祝你有美好的一天;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多