presidio icon indicating copy to clipboard operation
presidio copied to clipboard

ItVatCodeRecognizer result span includes the space after the VAT code

Open chrikrah opened this issue 1 month ago • 3 comments

Describe the bug

The ItVatCodeRecognizer pattern at it_vat_code.py:28 also takes a separator after the last digit. When a space follows a valid code, the result ends one character late, and after anonymization the next word sticks to the placeholder.

r"\b([0-9][ _]?){11}\b"

To Reproduce

from presidio_analyzer.predefined_recognizers import ItVatCodeRecognizer
from presidio_anonymizer import AnonymizerEngine

text = "P.IVA 01333550323 del cliente"
results = ItVatCodeRecognizer().analyze(text, ["IT_VAT_CODE"])
for r in results:
    print(r.start, r.end, repr(text[r.start:r.end]))
print(AnonymizerEngine().anonymize(text=text, analyzer_results=results).text)
$ venv/bin/python -I it_vat.py
6 18 '01333550323 '
P.IVA <IT_VAT_CODE>del cliente
# presidio-analyzer and presidio-anonymizer from main at 05b60e1, Python 3.12.3
# not run: AnalyzerEngine with an Italian NLP model; the span comes from the pattern alone

The code is the valid one from tests/test_it_vat_code_recognizer.py. In each test case the code ends the text, so no test sees the extra character.

Expected behavior

6 17 '01333550323' and P.IVA <IT_VAT_CODE> del cliente. The RecognizerResult docstring says end is "the end location of the detected entity". The space is not part of the code.

Additional context

A pattern that puts the separator only between digits fixes it:

r"\b[0-9](?:[ _]?[0-9]){10}\b"

It keeps the inner separators, so 01333550_323 still gives (0, 12). With it, the repro prints the expected output and pytest -q tests/test_it_vat_code_recognizer.py gives 5 passed, as on 05b60e1.

Is the trailing separator matched on purpose, or is the pattern change the fix you'd want?

chrikrah avatar Nov 05 '26 08:11 chrikrah

Hi @chrikrah, thanks for the clear repro! I'd like to open a PR for this. One note on the suggested pattern: with \b at the end, a code followed by _ (e.g. 01333550323_ ok) stops matching entirely, since _ is a word character. Using a lookahead keeps the same accepted inputs as today and just ends the span at the last digit:

r"\b[0-9](?:[ _]?[0-9]){10}(?=[ _]?\b)"

I've tested it with your example and added tests for a trailing space, a trailing underscore, internal spaces, and a 12-digit number. Opening a PR shortly.

AisiriMR avatar Nov 07 '26 20:11 AisiriMR

Hi! I'd like to work on this. I'll use the pattern suggested in the issue (\b[0-9](?:[ _]?[0-9]){10}\b) so separators are only allowed between digits, and add test cases where the code is followed by more text. I'll open a PR shortly.

shlokbam avatar Nov 08 '26 05:11 shlokbam

Sorry, I missed that @AisiriMR already has #2463 open; I'll leave this one to them.

shlokbam avatar Nov 08 '26 05:11 shlokbam