Reputation: 467
I have a list variable name
:
name = ['Ny-site-1-145237890-service']
I want to split this list in a way so I can get name = ['Ny-site-1']
.
To do this I am using the below code:
import re
name = ['Ny-site-1-145237890-service']
site_name = re.split('(-[0-9]-service)')[0]
But the above code is not give me the output I am looking for. How do I get the desired result?
Upvotes: 0
Views: 57
Reputation: 473803
First of all, re.split()
requires 2 arguments, you are providing a single one.
Also, you need to add +
quantifier (means "1 or more") for the [0-9]
set of characters:
>>> import re
>>>
>>> name = ['Ny-site-1-145237890-service']
>>> re.split(r'-[0-9]+-service', name[0])[0]
'Ny-site-1'
I would also add the maxsplit=1
argument to avoid unnecessary splits:
>>> re.split(r'-[0-9]+-service', name[0], maxsplit=1)[0]
'Ny-site-1'
You may also add an end of a string check to make the expression more reliable:
-[0-9]+-service$
And, you can also solve it with re.sub()
:
>>> re.sub(r'-[0-9]+-service$', '', name[0])
'Ny-site-1'
Upvotes: 2
Reputation: 7100
Try adding a +
in your regex to match multiple numbers.
name = 'Ny-site-1-145237890-service'
site_name = re.split('(-[0-9]+-service)', name)[0]
If you want to use an array to store your name(s), you can use
name = ['Ny-site-1-145237890-service']
site_name = re.split('(-[0-9]+-service)', name[0])[0]
If you have multiple names and you want to print them all, you can use
for i in names:
print(re.split('(-[0-9]+-service)', i)[0])
Upvotes: 0