【问题标题】:Regular expression to find a number ends with special character in Swift在 Swift 中查找以特殊字符结尾的数字的正则表达式
【发布时间】:2021-12-29 04:40:42
【问题描述】:

我有一个字符串数组,例如:

"Foo", "Foo1", "Foo$", "$Foo", "1Foo", "1$", "20$", "1$Foo", "12$$",  etc.

我需要的格式是[Any number without dots][Must end with single $ symbol](我的意思是,上面数组中的 1$ 和 20$)

我尝试了以下方法,但它不起作用。

func isValidItem(_ item: String) -> Bool {
   let pattern = #"^[0-9]$"#
   return (item.range(of: pattern, options: .regularExpression) != nil)
}

有人可以帮我解决这个问题吗?此外,如果您有任何关于正则表达式模式的信息,请分享一些很棒的链接。

谢谢

【问题讨论】:

  • 我对 swift 一无所知,但不一定非得是^[0-9]+\$$
  • #"^[0-9]$"# 不是只允许一位数字吗?也许^\d+$ 能做到这一点?不要犹豫,使用像 regex101.com 这样的在线正则表达式来测试你的正则表达式,然后将它应用到 Swift 上。
  • #"^[0-9]+\$$"# 或更好 - #"^[0-9]+\$\z"#

标签: swift regex nsregularexpression


【解决方案1】:

你可以使用

func isValidItem(_ item: String) -> Bool {
   let pattern = #"^[0-9]+\$\z"#
   return (item.range(of: pattern, options: .regularExpression) != nil)
}

let arr = ["Foo", "Foo1", "Foo$", "$Foo", "1Foo", "1$", "20$", "1$Foo", "12$$"]

print(arr.filter {isValidItem($0)})
// => ["1$", "20$"]

这里,

  • ^ - 匹配行首
  • [0-9]+ - 一个或多个 ASCII 数字(请注意,Swift regex engine is ICU\d 匹配此风格中的任何 Unicode 数字,因此如果您只需要匹配 0-9 范围内的数字,[0-9] 更安全)
  • \$ - 一个 $ 字符
  • \z - 字符串的最后。

查看online regex demo(使用$ 代替\z,因为演示是针对单个多行字符串运行的,因此在regex101.com 上使用m 标志)。

【讨论】:

    猜你喜欢
    • 2018-06-13
    • 2021-12-29
    • 1970-01-01
    • 2016-04-28
    • 2010-12-02
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多