Search code examples
pythonpython-3.xregexarabicfarsi

How to split str, that contains farsi and english words using re module on python


I have some_str = 'دریافت اطلاعات در مورد HDD {hdd}'. I need regex for splitting this by farsi and non farsi words for getting result like this: ['دریافت اطلاعات در مورد', 'HDD {hdd}']

import re
some_str = 'دریافت اطلاعات در مورد HDD {hdd}'
regex = '???'
re.split(regex, some_str)

For another str like "اضافه کردن اعلام کننده {notifier} روی سرور {host} بوسیله کاربر {role}/{user} از آدرس های IP {ip_address}" i expect next result:

['اضافه کردن اعلام کننده', '{notifier}', 'روی سرور', '{host}', 'بوسیله کاربر', '{role}/{user}', 'از آدرس های', 'IP {ip_address}']


Solution

  • You may use this re.split:

    import re
    # regex for arabic text
    reg = re.compile('([\u0600-\u06FF]+(?:\s+[\u0600-\u06FF]+)*)\s*')
    
    # or for matching Persian characters only use:
    # [\u0622\u0627\u0628\u067E\u062A-\u062C\u0686\u062D-\u0632\u0698\u0633-\u063A\u0641\u0642\u06A9\u06AF\u0644-\u0648\u06CC]
    
    some_str = 'دریافت اطلاعات در مورد HDD {hdd}'
    lst1 = list(filter(None, reg.split(some_str)))
    print (lst1)
    ## ['دریافت اطلاعات در مورد', 'HDD {hdd}']
    
    s = "اضافه کردن اعلام کننده {notifier} روی سرور {host} بوسیله کاربر {role}/{user} از آدرس های IP {ip_address}"
    lstw = list(filter(None, reg.split(s)))
    print (lst2)
    ## ['اضافه کردن اعلام کننده', '{notifier} ', 'روی سرور', '{host} ', 'بوسیله کاربر', '{role}/{user} ', 'از آدرس های', 'IP {ip_address}']
    

    \[\u0600-\u06FF\] is used to match Persian characters.

    RegEx Details:

    • ([\u0600-\u06FF]+(?:\s+[\u0600-\u06FF]+)*): Match space separated Persian text at the start in capture group #1
    • \s*: Match 0 or more whitespaces
    • (.*): Match remainder of string in capture group #2