Home > Software engineering >  Match everything other than a specific pattern in a number
Match everything other than a specific pattern in a number

Time:12-31

I am trying to match everything in a phone number other than a specific pattern.

In the number "07440359359" is there a way to match everything other than "359"?

My main aim with this is to be able to replace the last digit in the number that is not in the pattern.

For example:

With 07440359359 the desired output is 0744*359359

I've come up with this pattern so far ^(?!.*(359)) but it does not match everything other than the pattern.

Any ideas would be greatly appreciated! :)

CodePudding user response:

I think you'd want:

\d((?:359)*)$

See an online demo


  • \d - A single digit;
  • ((?:359)*) - A 1st capture group to match '359' (greedy);
  • $ - End string anchor.

Replace with *\1


import re
s = "07440359359"
print(re.sub(r'\d((?:359)*)$', r'*\1', s))

Prints:

0744*359359

CodePudding user response:

Why don't you use a regex with capturing groups and a lookbehind?

s = "07440359359"

import re

out = re.sub(r'(\d ?)((?:359) )', r'\1*\2', s)

output: '07440*359359'

If you want to ensure that the 359 are the last digits:

s = "074403593594"

import re

re.sub(r'(\d ?)((?:359) )(?!\d)', r'\1*\2', s)

output: 074403593594

  • Related