Issue with regex separating slug and lastname in a list

Viewed 53

My string is:

test_string = "@@@__slug1^^__firstname lastname@@@^^^ @@@__slug2^^__firstname1 lastname1@@@^^^"

I am trying to separate slug and lastname in a list my output will be like.

slug_list = [slug1,slug2]
name_list=[firstname lastname,firstname1 lastname1]

I try to first search all the slug my code for the same is.

import re
test_string = "@@@__slug1^^__firstname lastname@@@^^^ @@@__deletepurpose^^__Delete Purpose@@@^^^"
pattern = "@@@__\|(''*?)\|^^"
substring = re.search(pattern, test_string).group(1)
print(substring)

But it does not find a match as it is giving me the AttributeError: 'NoneType' object has no attribute 'group' error.

What is wrong with the pattern I am using?

1 Answers

You can use

@@@__(.*?)\^\^__(.*?)@@@\^\^\^

See the regex demo. Details:

  • @@@__ - a literal string
  • (.*?) - Group 1: any zero or more chars other than line break chars, as few as possible
  • \^\^__ - a ^^__ literal string
  • (.*?) - Group 2: any zero or more chars other than line break chars, as few as possible
  • @@@\^\^\^ - a literal @@@^^^ string.

See the Python demo:

import re
test_string = "@@@__slug1^^__firstname lastname@@@^^^ @@@__deletepurpose^^__Delete Purpose@@@^^^"
pattern = r"@@@__(.*?)\^\^__(.*?)@@@\^\^\^"
matches = re.findall(pattern, test_string)
print("Slug list:", [x for x,y in matches])
print("Name list:", [y for x,y in matches])

Output:

Slug list: ['slug1', 'deletepurpose']
Name list: ['firstname lastname', 'Delete Purpose']
Related