Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading