0

I have

s = "[[[ab_1]]] bla1 [[[cd_3]]] bla2 "

I want to split s into "bla1" and "bla2". the thing is, ab_1 and cd_3 are dynamic literals. they can be anything in form "letters_numbers".

I am stuck like never before.. I tried with split() but it is getting ugly because s can be a long string with multiple delimeters in it..

any pythonic ideas?

2
  • regex ? import re ; re.search|match won't do it ? Commented Jan 9, 2015 at 23:31
  • Can you post what the exact answer would look like for the given string s? Commented Jan 9, 2015 at 23:32

4 Answers 4

2

I think you want to use re.split.

Something like the following regular expression might do it:

In [11]: re.split("\s*\[{3}.*?\]{3}\s*", s)
Out[11]: ['', 'bla1', 'bla2 ']

In [12]: re.split("\s*\[{3}.*?\]{3}\s*", s.strip())[1:]
Out[12]: ['bla1', 'bla2']
Sign up to request clarification or add additional context in comments.

Comments

2
s = "[[[ab_1]]] bla1 [[[cd_3]]] bla2 "

import  re

print(re.findall("(?<=\s)\w+",s))
['bla1', 'bla2']

Or if you want to include punctuation:

s = "[[[ab_1]]] bla1 [[[cd_3]]] bla2!"

import re

print(re.findall(r"\s(\w+\S)",s)
['bla1', 'bla2!']

1 Comment

@ReutSharabani, because the OP onlys wants the two words.
1

You can split the string and use str.isalnum() in a list comprehension :

>>> [i for i in s.split() if i.isalnum()]
['bla1', 'bla2']

Comments

1
import re

s = "[[[ab_1]]] bla1 [[[cd_3]]] bla2 "
print filter(bool, re.split('\W', s))

OUTPUT:

['ab_1', 'bla1', 'cd_3', 'bla2']

And if you want only the "bla"s:

s = "[[[ab_1]] bla1 [[[cd_3]]] bla2 "
print filter(lambda x: re.match('\w+|\s+', x), re.sub('\[.*?\]', ' ', s))

will output:

bla1   bla2 

3 Comments

not not x? What is that about?
@khelwood just messing with you :) you can use lambda x:x and it'll work just fine
Functionally the same as just using filter(bool, re.split('\W', s)) then. I just wondered why someone would think not not x was necessary.

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.