How to extract a string from a PDF + Text

I am attempting to extract a four-digit numerical string from a number of PDFs that have been OCR’d. I want to place an extracted numerical string into a metadata field for the item in DEVONthink Pro.

The string is consistently contained in a format represented by the following examples:

***** 4321 YES

***** 5678 NO

***** 9876 MAYBE

An alpha-numeric string like this only appears once in a PDF.

I’ve analysed many such PDFs and have found that the alpha-numeric string appears as one line in the plain text layer.

Further, the five asterisk and one space that appear before the four digits are unique in each PDF.

In the first example, I want to extract 4321.

In the second, 5678.

And in the third, 9876.

In each case, I want the four-digit numeric string, for example 9876, to be added to a particular metadata field for the item.

My guess is this is a job for a smart rule, but I’m not sure whether I would also need Apple Script.

Unfortunately, quite a bit of time searching and talking to AI has not revealed a workable solution, so I’m hoping somebody might be able to suggest a way of doing this. Many thanks.

Potentially, I could use the action “Scan Text” in a Smart Rule:

but, as the * is used to represent the text to capture, I’m not sure how it works with preceding characters being five asterisk and one space. Also in some cases the following word is YES, in other cases, NO or MAYBE, and I’m not sure how to account for that.

I notice Regular Expression is an alternative to String so I’ll investigate that, but happy for any pointers as well.

Use a regular expression like
\*{5}\s+(\d{4})\s+(?:YES|NO|MAYBE) in the scan text action
and \1 to refer to the four digits in the metadata replacement

4 Likes

Thank you so much. Yes, I’ve just independently got to almost the same answer. I think the gap for the space was a bit uncertain and so a code that allowed for any type of blank space was used. I’ve got it working with regex in a script so very pleased.

2 Likes

Good, though a script is not really needed here. In the “Scan Text” action, select “Regular Expression” instead of “String” to the left of the text field.

To explain the RE:
\*{5}: exactly five asterisk
\s+: at least one white space (space, horizontal tab etc)
(\d{4}): exactly four digits, captured in a group – that’s what \1 refers to in the metadata setting later
(?:YES|NO|MAYBE): Any of these strings as an “alternation” | in a non-capturing group (?:...). You can’t refer to this string later – if that’s needed, use () instead of (?:)

3 Likes