leo04 leo04 - 3 months ago 9x
Python Question

Treat regular expression between dashes

As I'm really noob using regex, please could you help me to use "sub" to change te numbers of these expressions:




context: samsung-j7-duos-dual-chip-desbloqueado-oi-android-5.1-tela-5.5-16gb-wi-fi-4g-camera-13mp-branco&AFL-03-171644black

In need to replace the numbers after the second dash for other numbers (let's say 987654).

The number after the second dash, as you can see in the examples, may vary in number of digits but they are always numbers.

The digits after de first dash are always 0X (X = 1,2 or 3).

The examples I gave are part of a bigger strings, so other "-" and "&" may appear anywhere else in the string, inclusively multiple times.

Thanks you all!


(?<=&AFL-\d\d-)(\d+) Will match the digits you want to replace, using a positive lookbehind, which ensures &AFL-XX- is there, but does not match them.

Combine this with re.sub()

re.sub(r"(?<=&AFL-\d\d-)(\d+)", string_to_fix, digits_you_want)