Given a string #abcde#jfdkjfd, how can I get the string between two # ? And I also want that if no # pair(means no # or only one #), the function will return None.
-
It seems you can achieve this with a basic regular expression. Have a look at regular-expressions.info.Felix Kling– Felix Kling2011-12-19 09:40:04 +00:00Commented Dec 19, 2011 at 9:40
3 Answers
Use (?<=#)(\w+)(?=#) and capture the first group. You can even cycle through a string which contains several embedded strings and it will work.
This uses both a positive lookbehind and positive lookahead.
2 Comments
If you don't insist on regular expressions and are willing to accept an empty list instead of None for the case where there are no results then the easy way is:
>>> "#abcde#jfdkjfd".split('#')[1:-1]
['abcde']
Note that the result really has to be a list as you could have more than one result.
If you insist on getting None instead of an empty list (though not perfect as this would also turn any empty string into None):
>>> "#abcde#jfdkjfd".split('#')[1:-1] or None
['abcde']
If you only wanted the first marked string then you could do this:
>>> def first_marked(s):
token = s.split('#')
if len(token) >= 3:
return token[1]
else:
return None
>>> first_marked("#abcde#jfdkjfd")
'abcde'