Skip to content
Advertisement

Treat regular expression between dashes

Could you help me to use “sub” to change the numbers of these expressions:

&AFL-03-123456

&AFL-01-12345

&AFL-02-123

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.

Advertisement

Answer

(?<=&AFL-dd-)(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-dd-)(d+)", string_to_fix, digits_you_want)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement