Applescript Grep & found text


I’m using the following script to proceed some grep find / change within applescript

use framework "Foundation"

on replacePattern:thePattern inString:theString usingThis:theTemplate
	set theRegEx to current application's NSRegularExpression's regularExpressionWithPattern:thePattern options:0 |error|:(missing value)
	set theResult to theRegEx's stringByReplacingMatchesInString:theString options:0 range:{location:0, |length|:length of theString} withTemplate:theTemplate
	return theResult as text
end replacePattern:inString:usingThis:

This is called via.

set myRegEx to "Product ID: (\d+)"
set myCovertedAsciiText2 to (re's replacePattern:myRegEx inString:myCovertedAsciiText2 usingThis:"MyProduct ID: [FOUND NUMBER HERE]")

In Indesign & Text Wrangler I can ‘bring back’ the bracketed found text by using $1 or \1, Does anyone know the syntax to do this here?

I’ve tried delimiting the \1 but I can’t get it to work.

many thanks


According to the NSRegularExpression documentation you shouldn’t use the standard back reference format \n but should use only $n. Since you have already tried with the dollar sign the template “MyProduct ID: $1” should be fine. So my question would be does the regex even match?

Or even compile, without another backslash before the d+.

yep spotted the extra backslash “ thanks Shane

Still not sure what’s going on as my actual grep search works in Text wrangler, but not in applescript.

Thanks DJ Bazzie Wazzie for the $1 Ive tested this on a simpler search and it works great.