HI, I am trying to construct a regEx pattern to match a UK tax code.
The pattern i have created is

"^(/BR{1}/|/D0{1}/|/NT{1}/)|^(([Kk]{1}[1-9]{1}[0-9]{2,3})|([1-9]{1}[0-9]{2,3}[LPTYlpty]{1}))"

I thought this would match the codes as BR or D0 or NT or K followed by 3 or 4 digits or 3 or 4 digits followed by L P T or Y.

However it does not work. I am quite new to regex and would be most greatful for any help.

thanks

Dani AI

Generated

Nice work — your last change shows you fixed the main problems. Two quick points that explain the earlier failures: you had literal slash delimiters (e.g. /BR/) which are used in some languages but must not appear inside a Python regex string, and placing ^/$ around separate alternation branches can let some branches match only part of the input. Also {1} is redundant.

A compact, anchored expression that is easier to read uses a single alternation and non‑capturing grouping. For example:

pattern = r'^(?:BR|D0|NT|[Kk][1-9]\d{2,3}|\d{3,4}[LlPpTtYy])$'

Use re.fullmatch(pattern, code, flags=re.I) in modern Python or re.match with the anchors in older versions. Use a raw string (r'...') so backslashes are handled correctly, and compile the pattern once if you test many codes.

Notes: decide whether numeric parts may start with zero — if so replace [1-9]\d{2,3} with \d{3,4}. Regex checks format only; if you need authoritative tax-code validation, consult the issuing documentation. Overall, your final approach was correct — the fixes above simply make it cleaner, more maintainable, and Python-friendly.

hi...further info

have played about with the pattern slightly so that it is now

"^(/BR|D0|NT/{1}$)|^(([Kk]{1}[1-9]{1}[0-9]{2,3}$)|([1-9]{1}[0-9]{2,3}[LPTYlpty]{1}$))"

and the second part of the patern works fine....just the BR D0 and NT do not work now.

Thanks for any help

Hi there sorry to have waisted your time have solved it...I think...lol pattern now reads

"^(BR|D0|NT)$|^(([Kk]{1}[1-9]{1}[0-9]{2,3}$)|([1-9]{1}[0-9]{2,3}[LPTYlpty]{1}$))"

Thanks for looking

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.