2

I want to match or with the string I obtain and group the result based on the times or occurs.

My input will be like:

a or b*~c or 27*y or 5*~b

so my output should be:

a, b*~c, 27*y, 5*~b

My code works if there are exactly 3 or, but returns [] otherwise.

I am new to python and I don't understand exactly how the pattern must be given to the compile function.

import re
input = raw_input(" ")

ans = re.compile(r'(.*) or (.*) or (.*) or (.*)')
print re.findall(ans, input)
1
  • Simply split your string using str.split('or'). re.split is expected to be slower, Commented Oct 30, 2015 at 5:46

2 Answers 2

2

Just do splitting according to the sub-string or

re.split(r' or ', s)

or

re.split(r'\s+or\s+', s)
Sign up to request clarification or add additional context in comments.

Comments

1

You can do a simple split without any use of re.

input = raw_input()
ans = input.split("or")

or

ans = input.split(" or ")

If you want to use findall you can use

x="a or b*~c or 27*y or 5*~b"
print re.findall(r"(?:^|(?<=\bor\b))\s*(.*?)\s*(?=\bor\b|$)",x)

For both * and or use

x="a or b*~c or 27*y or 5*~b"
print [i.split("*") for i in x.split(" or ")]

Output:[['a'], ['b', '~c'], ['27', 'y'], ['5', '~b']]

2 Comments

And the deference is: First one returns ['foo ', ' bar'] and the second one returns ['foo', 'bar'] (says that the string is foobar).
@vks how can I split both 'or' and '*'? Basically reducing them to list of lists. My answer should be [[a], [b,~c], [27,y], [5,~b]] Thanks

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.