1

I have this string, I want to remove numbers that have two decimal places and also three decimal places, however, for numbers that contain two decimal places, I don't want to remove the first two numbers that are in the string, this is my code.

import re
string = "air max 12 x clot infantil 16 26 67 80 272 117 160"
regex = re.sub(r"\d{3}", "", string)           
print(regex)

Well, notice that I can eliminate numbers that have 3 decimal places, but those that contain two I can't. Even if my code is this:

import re
string = "air max 12 x clot infantil 16 26 67 80 272 117 160"
regex = re.sub(r"\d{2,3}", "", string)           
print(regex)

This works, the problem is that it will remove the first two numbers that have two decimal places, the output I wanted was:

import re
string = "air max 12 x clot infantil 16 26 67 80 272 117 160"
regex = re.sub(r"\d{2,3}", "", string)
//something here
print(regex)
Expected output
air max 12 x clot infantil

How can I do this using regex?

3
  • in your example there are no decimal places in the string for the numbers, did you mean a length of 2 or 3? Commented Jun 25, 2021 at 3:15
  • You're right, I was wrong in the term of decimal places, but I think I could more or less understand the question, if I can't edit Commented Jun 25, 2021 at 3:17
  • @etch_45 yes I meant it Commented Jun 25, 2021 at 3:18

1 Answer 1

1

You can use following regex: '[a-zA-Z].*[a-zA-Z]', it will match anything starting from alphabet and ending on alphabet.

>>> re.findall('[a-zA-Z].*[a-zA-Z]', string)
['air max 12 x clot infantil']

Sign up to request clarification or add additional context in comments.

6 Comments

This is exactly what I need, but I don't want to leave it in a list []
Just take the first item from it.
I didn't mention it in the question, but I'll have many items, and there's no way for me to know all the indexes, although I can go through the list with for, do you have any solution for this? +1
You can just iterate the list, or you can just use re.finditer to get an iterator of matches and iterate over them. Also it'd be better to add such a example that matches I didn't mention it in the question, but I'll have many items
Obs, I noticed that if I change the string to "air max 90" it only displays "air max" why does this happen?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.