fjcaetano / NSStringMask

NSStringMask allows you to apply masks or formats to NSStrings using NSRegularExpression to input your format.
http://fjcaetano.github.io/NSStringMask/
MIT License
241 stars 36 forks source link

currency mak #14

Closed BesatZardosht closed 7 years ago

BesatZardosht commented 7 years ago

I would like to create a NSStringMask for money format in Swift:

let myMask: NSStringMask = NSStringMask.init(pattern: "^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\\.[0-9]{2})?$") but I will get error in runtime: EXC_BAD_INSTRACTION

What am I doing wrong?

fjcaetano commented 7 years ago

@BesatZardosht what are you trying to achieve? The first thing you must have in mind is that NSStringMask only works if you have at least one group parenthesis, and you have none. By adding ?: right after opening parenthesis you're explicitly telling the regex interpreter not to use the parenthesis group as a result group. Also, it appears your regex is missing escape back-slashes before that last dollar sign $.

If you're trying to add dots and commas to a currency input, I don't think NSStringMask will work because it reads from left to right and it would need to read from right to left in order to do it:

Imagine you have the number 123456. If you read from left to right, you'd read 3 characters and add a comma, which would yield 123,456$.

In order to properly mask 123456 you need to read it from right to left: 1 - Read two characters and place a dot: 1234.56 2 - Read 3 more characters and place a comma: 1,234.56

As I said, NSStringMask doesn't read from right to left so I don't think there's a pattern that would do what I think you're asking. If you want to improve NSStringMask in order for it to be achievable, you're more than welcome, just submit a pull request and I'll review it.

fjcaetano commented 7 years ago

Btw, a good tool to test your Regexes is http://regexr.com/

fjcaetano commented 7 years ago

Closing due to inactivity