0

Suppose I have a expression

exp="\"OLS\".\"ORDER_ITEMS\".\"QUANTITY\"  <50 and  \"OLS\".\"PRODUCTS\".\"PRODUCT_NAME\"  = 'Kingston' or \"OLS\".\"ORDER_ITEMS\".\"QUANTITY\"  <20"

I want to split the expression by and , or so that my result will be

exp=['\"OLS\".\"ORDER_ITEMS\".\"QUANTITY\"  <50','\"OLS\".\"PRODUCTS\".\"PRODUCT_NAME\"  = 'Kingston'','\"OLS\".\"ORDER_ITEMS\".\"QUANTITY\"  <20']

This is what i have tried:

import re
res=re.split('and|or|',exp)

but it will split by each character how can we make it split by word?

3
  • Yes and what is your issue exactly? Have you googled 'split string python'? Commented Nov 20, 2020 at 4:52
  • yes shown what i have tried Commented Nov 20, 2020 at 4:55
  • @Julien with split string we cannot pass multiple delimiters right? Commented Nov 20, 2020 at 4:55

3 Answers 3

1
import itertools
exp=itertools.chain(*[y.split('or') for y in exp.split('and')])
exp=[x.strip() for x in list(exp)]

Explanation: 1st split on 'and'. Now try spitting each element obtained on 'or'. This will create list of lists. Using itertools, create a flat list & strip extra spaces from each new element in the flat list

Sign up to request clarification or add additional context in comments.

Comments

1

Your regex has three alternatives: "and", "or" or the empty string: and|or|

Omit the trailing | to split just by those two words.

import re
res=re.split('and|or', exp)

Note that this will not work reliably; it'll split on any instance of "and", even when it's in quotes or part of a word. You could make it split only on full words using \b, but that will still split on a product name like 'Black and Decker'. If you need it to be reliable and general, you'll have to parse the string using the full syntax (probably using an off-the-shelf parser, if it's standard SQL or similar).

Comments

0

You can do it in 2 steps: [ss for s in exp.split(" and ") for ss in s.split(' or ')]

1 Comment

but it wont be dynamic I guess if I have a expression with only and exp="\"OLS\".\"ORDER_ITEMS\".\"QUANTITY\" <50 and \"OLS\".\"PRODUCTS\".\"PRODUCT_NAME\" = 'Kingston' ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.