pattern to extract linkedin username from text

Viewed 137

I am trying to extract linkedin url that is written in this format,

text = "patra 12 EXPERIENCE in / in/sambhu-patra-49b4759/ 2020 - Now O Skin Curate Research Pvt Ltd Embedded System Developer, WB 0 /bindasssambhul O SKILLS LANGUAGES Arduino English Raspberry Pi Movidius Hindi Bengali ICS Intel Compute Stick PCB Design Python UI Design using Tkinter HOBBIES HTML iti CSS G JavaScript JQuery IOT\n"


pattern = \/?in\/.+\/?\s+

I need to extract this in/sambhu-patra-49b255129/ from the any noisy text like the one above,

It's a linkedin url written in short form.

My pattern is not working

5 Answers

You can use

m = re.search(r'\bin\s*/\s*(\S+)', text)
if m:
  print(m.group(1))

See the regex demo.

Details:

  • \b - word boundary
  • in - a preposition in
  • \s* - zero or more whitespaces
  • / - a / char
  • \s* - zero or more whitespaces
  • (\S+) - Capturing group 1: any one or more whitespaces.

Another option matching word characters, optionally repeated by a - and word characters with an optional / at the end:

(?<!\S)in/\w+(?:-\w+)*/?

The pattern matches:

  • (?<!\S) Assert a whitspace boundary to the left
  • in/ Match literally
  • \w+(?:-\w+)* match 1+ word chars, optionally repeated by - and 1+ word chars
  • /? Match optional /

Regex demo

import re
s = ("patra 12 EXPERIENCE in / in/sambhu-patra-49b4759/ 2020 - Now O Skin Curate Research Pvt Ltd Embedded System Developer, WB 0 /bindasssambhul O SKILLS LANGUAGES Arduino English Raspberry Pi Movidius Hindi Bengali ICS Intel Compute Stick PCB Design Python UI Design using Tkinter HOBBIES HTML iti CSS G JavaScript JQuery IOT")
m = re.search(r"(?<!\S)in/\w+(?:-\w+)*/?", s)
if m:
    print(m.group())

Output

in/sambhu-patra-49b4759/

How about just:

text.split(" ")[5]

This can be done without using any regex:

>>> text = "patra 12 EXPERIENCE in / in/sambhu-patra-49b4759/ 2020 - Now O Skin Curate Research Pvt Ltd Embedded System Developer, WB 0 /bindasssambhul O SKILLS LANGUAGES Arduino English Raspberry Pi Movidius Hindi Bengali ICS Intel Compute Stick PCB Design Python UI Design using Tkinter HOBBIES HTML iti CSS G JavaScript JQuery IOT\n"
>>> s = text[text.find(' in/')+1:]
>>> print (s[0:s.find(' ')])
in/sambhu-patra-49b4759/

Here is one of the ways.

regex = re.compile("\/\s?in\/(.*?)\/")
def check(str):
    search = re.search(regex, str)
    if search is not None:
        print(search.group(1))

Output

sambhu-patra-49b4759
Related