Home > OS >  Regular expression to find a number ends with special character in Swift
Regular expression to find a number ends with special character in Swift

Time:11-18

I have an array of strings like:

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

My required format is [Any number without dots][Must end with single $ symbol] (I mean, 1$ and 20$ from the above array)

I have tried like the below way, but it's not working.

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

Can some one help me on this? Also, please share some great links to learn about the regex patterns if you have any.

Thank you

CodePudding user response:

You can use

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$"]

Here,

  • ^ - matches start of a line
  • [0-9] - one or more ASCII digits (note that Swift regex engine is ICU and \d matches any Unicode digits in this flavor, so [0-9] is safer if you need to only match digits from the 0-9 range)
  • \$ - a $ char
  • \z - the very end of string.

See the online regex demo ($ is used instead of \z since the demo is run against a single multiline string, hence the use of the m flag at regex101.com).

  • Related