Auto-generate from MetaData "PubDate"

I am using Devonthink 4.1.1, which I use primarily to organize and search through my PDF library.

I created a Custom Metadata, entitled “PubYear” (Integer Number). Which appears on the right navigation side bar under “Data.”

Question: Is there a way to auto-populate PubYear by prompting Devonthink to extract the years between parentheses?

For example:

Guido Starosta - “Cognitive Commodities and the Value-Form” (Science and Society) (2012)
Meredith L. McGill - American Literature and the Culture of Reprinting, 1834-1853 (Penn) (2003)
Benedict Anderson - Imagined Communities (Verso) (1983) (2006)*

For each of those files, the PubYear would be populated, respectively, as:

2012
2003
1983*

*if there are two years, the first should be recorded

Do I i need an add-on or plug-in? Or develop an automated script?

Thank you in advance!

Here’s a simple example script:

tell application id "DNtp"
	set theRecords to selected records
	repeat with theRecord in theRecords
		set recordName to name of theRecord
		set tid to AppleScript's text item delimiters
		set AppleScript's text item delimiters to "("
		set parts to text items of recordName
		set AppleScript's text item delimiters to tid
		if (count of parts) > 1 then
			set afterParen to item -1 of parts
			set tid to AppleScript's text item delimiters
			set AppleScript's text item delimiters to ")"
			set yearPart to text item 1 of afterParen
			set AppleScript's text item delimiters to tid
			if (length of yearPart) ≥ 4 then
				set yearValue to yearPart as integer
				if yearValue > 1800 and yearValue < 2100 then -- reasonable year range
					add custom meta data yearValue for "PubYear" to theRecord as "int"
				end if
			end if
		end if
	end repeat
end tell

It worked! What an elegant solution. Thank you so much.

I thought a batch process with Scan name: Regular Expression might be enough. But I guess that only works if the metadata field has one of the text data types. (It returns a string, not an integer.)

As a little exercise, I wrote a JavaScript version of @cgrunenberg’s script:

(() => {
	const DT = Application("DEVONthink");
	DT.selectedRecords().forEach(r => {
		const foundYear = r.name().match(
			/\((\d{4})\)(?:\s?\(\d{4}\))?/
		);
		foundYear && foundYear[1] > 1800 && foundYear[1] < 2100
			? DT.addCustomMetaData(foundYear[1], {for:"PubYear", to:r})
			: undefined;
	});
})()

It uses RegEx instead of AppleScript's text item delimiters, and JS automatically converts the string to an integer.