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

Python regular expression split by multiple delimiters

Given the sentence "I want to eat fish and I want to buy a car. Therefore, I have to make money."

I want to split the sentene by

[‘I want to eat fish’, ‘I want to buy a car", Therefore, ‘I have to make money’]

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

I am trying to split the sentence

re.split('.|and', sentence)

However, it splits the sentence by ‘.’, ‘a’, ‘n’, and ‘d’.

How can I split the sentence by ‘.’ and ‘and’?

>Solution :

In addition to escaping the dot (.), which matches any non-newline character in regex, you should also match any leading or trailing spaces in order for the delimiter of the split to consume undesired leading and trailing spaces from the results. Use a positive lookahead pattern to assert a following non-whitespace character in the end to avoid splitting by the trailing dot:

re.split('\s*(?:\.|and)\s*(?=\S)', sentence)

This returns:

['I want to eat fish', 'I want to buy a car', 'Therefore, I have to make money.']

Demo: https://replit.com/@blhsing/LimitedVastCookies

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