0

Been struggling with this one for a while now - I simply can't wrap my brain around it.

Given the following string variations:

some text
some text http://a.link.to/something
some text - http://a.link.to/something
some text: http://a.link.to/something
http://a.link.to/something

I am looking for a RegEx that would produce the following:

{'text': 'some text',
 'link': ''}

{'text': 'some text',
 'link': 'http://a.link.to/something'}

{'text': '',
 'link': 'http://a.link.to/something'}

Cheers!

2
  • Does this help? Here's what it produces: ideone.com/FL1ehX Commented Mar 5, 2015 at 14:25
  • Works on regex101.com but it raises an error when I try to use it with re.search: invalid expression, bad character range. Commented Mar 5, 2015 at 16:06

2 Answers 2

3

Use named capturing groups in re.match function so that you could be able to create dictionary with user defined keys.

>>> s = '''some text
some text http://a.link.to/something
some text - http://a.link.to/something
some text: http://a.link.to/something
http://a.link.to/something'''
>>> for i in s.split('\n'):
        re.match(r'(?P<text>(?:(?!http://).)*?)\W*\b(?P<link>http://.*)?$', i).groupdict()


{'link': None, 'text': 'some text'}
{'link': 'http://a.link.to/something', 'text': 'some text'}
{'link': 'http://a.link.to/something', 'text': 'some text'}
{'link': 'http://a.link.to/something', 'text': 'some text'}
{'link': 'http://a.link.to/something', 'text': ''}
Sign up to request clarification or add additional context in comments.

1 Comment

Looks like I'm missing something. The last string isn't quite right: {'text': 'http://a.link.to/something', 'link': None}
1

You can use a regex like this:

(.+?)(http.*)?$

Working demo

enter image description here

As you can see is not fully achieving what you want for the case of:

some text - http://a.link.to/something

Since it generates:

{'text': 'some text - ',  'link': 'http://a.link.to/something'}
                    ^--- Dash here

But you can do a pre or post clean to the text.

I'm posting the answer since it might help you.

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.