Search code examples
swiftstringvalidationpersianfarsi

Check or validation Persian(Farsi) string swift


I searched over web pages and stack overflow about validation of a Persian(Farsi) language string. Most of them have mentioned Arabic letters. Also, I want to know if my string is fully Persian(not contain). for example, these strings are Persian:

"چهار راه"

"خیابان."

And These are not:

"خیابان 5"

"چرا copy کردی؟"

Also, just Persian or Arabic digits are allowed. There are exceptions about [.,-!] characters(because keyboards are not supported these characters in Persian)

UPDATE: I explained a swift version of using regex and predicate in my answer.


Solution

  • After a period I could find a better way:

    extension String {
     var isPersian: Bool {
            let predicate = NSPredicate(format: "SELF MATCHES %@",
                                        "([-.]*\\s*[-.]*\\p{Arabic}*[-.]*\\s*)*[-.]*")
            return predicate.evaluate(with: self)
        }
    
    }
    

    and you can use like this:

    print("yourString".isPersian) //response: true or false
    

    The main key is using regex and predicate. these links help you to manipulate whatever you want:

    https://nshipster.com/nspredicate/

    https://nspredicate.xyz/

    http://userguide.icu-project.org/strings/regexp

    Feel free and ask whatever question about this topic :D

    [EDIT] The following regex can be used to accept Latin numerics, as they are mostly accepted in Persian texts

    "([-.]*\\s*[-.]*\\p{Arabic}*[0-9]*[-.]*\\s*)*[-.]*"