2

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.

1
  • It seems you can achieve this with a basic regular expression. Have a look at regular-expressions.info. Commented Dec 19, 2011 at 9:40

3 Answers 3

9
>>> import re
>>> s = "abc#def#ghi#jkl"
>>> re.findall(r"(?<=#)[^#]+(?=#)", s)
['def', 'ghi']

Explanation:

(?<=#)  # Assert that the previous character is a #
[^#]+   # Match 1 or more non-# characters
(?=#)   # Assert that the next character is a #
Sign up to request clarification or add additional context in comments.

Comments

2

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

You don't need a group at all since the lookarounds aren't part of the match.
Yes, that's true... Just a habit!
1

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'

Comments

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.