1

I have this text:

  u'times_viewed': 12268,
  u'url': u'/photo/79169307/30-seconds-light',
  u'user': {u'affection': 63962,

How can I just get out this string: "/photo/79169307/30-seconds-light"?

I am trying with regex and findall:

list = re.findall(‘u‘url‘: u‘/photo/"([^"]*)"‘, text)

but it won't go.

5
  • Did you try to read your string as json? Commented Aug 10, 2014 at 13:33
  • How did you try? Show us your regex. Commented Aug 10, 2014 at 13:36
  • That looks like output from a python data structure. If it is, maybe try: object_name['url'] instead of printing it out? If not, then could you post the relevant portion of your failing code? Commented Aug 10, 2014 at 13:37
  • Don't use list as a name. it is a builtin function. Commented Aug 10, 2014 at 13:45
  • Are you actually use accents instead of quotes/apostrophes? Commented Aug 10, 2014 at 13:57

1 Answer 1

2

I assume that by "it won't go," you mean that you get a syntax error, which you should. Here:

list=re.findall(‘u‘url‘: u‘/photo/"([^"]*)"‘,text)

you're using " when you mean '. This is causing a syntax error because " closes the string you're trying to pass re.findall. Try:

list_ = re.findall("u'url': u'/photo/([^']*)'", text)

Additionally, this isn't going to grab the text after photo, so you'll need to add more parens:

list_ = re.findall("u'url': u'(/photo/([^']*))'", text)

and now list_.group(1) should hold your string.

On top of that, it looks like you're dealing with JSON. A better approach might be:

import json
json.loads(text)
list_ = text['url']
Sign up to request clarification or add additional context in comments.

2 Comments

For your information: the regexes need to be closed with a quote charachter: re.findall("u'url': u'/photo/([^']*)'", text) and "u'url': u'(/photo/([^']*))'"
@xZise I think I fixed all of the typos. Let me know if there's anything else I missed.

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.