1

How do I extract a certain word after a certain character in regex python?

For example: given = 'abcdefghijkl"mnop:"qfdf"gg"'

I want to get qfdf which is afer "mnop:" and before "gg". The given string is one string, no whitespace.

So far I can do \w+"mnop:" to get to qfdf"gg", but I don't know any \K function in python regex. I am also aware of using (?<=...), but this only takes a fixed width of characters.

Thanks!

2
  • Have you tried anything? regexr.com is your friend. Commented Feb 9, 2017 at 4:49
  • @codeforester is regexr.com for python? I thought this was for js.. Commented Feb 9, 2017 at 4:56

1 Answer 1

1

Leverage lookarounds:

(?<="mnop:")[^"]+(?="gg")
  • The zero width positive lookbehind, (?<="mnop:"), makes sure the desired portion is preceded by "mnop"

  • [^"]+ matches one or more characters that are not "

  • The zero width positive lookahead, (?="gg"), makes sure the desired match is followed by "gg"

Example:

In [6]: given = 'abcdefghijkl"mnop:"qfdf"gg"'

In [7]: re.search(r'(?<="mnop:")[^"]+(?="gg")', given).group()
Out[7]: 'qfdf'
Sign up to request clarification or add additional context in comments.

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.