How to navigate the return values from calls to Cocoa Foundation framework

Hello,

I made the following call to get an array of ranges of a matching regex :

	set theText to current application's class "NSString"'s stringWithString:html
	set regexPattern to "url\\([" & (ASCII character 34) & ",'](https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w\\.-]*)*\\/?"
	set urlRegex to current application's class "NSRegularExpression"'s regularExpressionWithPattern:(regexPattern) options:(0) |error|:(missing value)
	set matchRanges to (urlRegex's matchesInString:(theText) options:(0) range:({0, theText's |length|()}))'s valueForKey:("range")

I get the following result :

item 1 of (NSArray) {(NSConcreteValue) NSRange: {11780, 52}, (NSConcreteValue) NSRange: {13066, 52}, (NSConcreteValue) NSRange: {15247, 40}, (NSConcreteValue) NSRange: {16288, 39}, (NSConcreteValue) NSRange: {17788, 36}, (NSConcreteValue) NSRange: {18596, 36}, (NSConcreteValue) NSRange: {19806, 75}, (NSConcreteValue) NSRange: {20807, 49}, (NSConcreteValue) NSRange: {21287, 63}, (NSConcreteValue) NSRange: {23892, 46}, (NSConcreteValue) NSRange: {24715, 35}, (NSConcreteValue) NSRange: {25182, 63}, (NSConcreteValue) NSRange: {25667, 44}, (NSConcreteValue) NSRange: {26011, 28}, (NSConcreteValue) NSRange: {26394, 66}, (NSConcreteValue) NSRange: {26769, 72}, (NSConcreteValue) NSRange: {28682, 66}, (NSConcreteValue) NSRange: {29576, 66}, (NSConcreteValue) NSRange: {31236, 32}}

The list of items is a NSArray which means I can’t do :

	repeat with range in matchRanges
		set element to range
		set pos to item 1 of element
		set len to item 2 of element
	end repeat

How do I get the position and length attributes of each NSRange ?
I have looked for AppleScript documentation on Apple Developer but can only find documents related to the scripting bridge.
Thanks,
Regards

Hi.

The matchesInString:options:range: method returns an array of NSTextCheckingResult objects, each of which represents a complete match of the regex pattern. If you’re only interested in complete matches, you can get the values of their range() properties all at once, and as an AppleScript list, by using the valueForKey: method as you have done and coercing the result to list:

set matchRanges to ((urlRegex's matchesInString:(theText) options:(0) range:({0, theText's |length|()}))'s valueForKey:("range")) as list

I haven’t analysed your regex pattern, but it looks as if it contains match groups (the parenthesised parts). If you want the individual ranges of those, you have to use the rangeAtIndex: method on each NSTextCheckingResult individually:

set urlRegex to current application's class "NSRegularExpression"'s regularExpressionWithPattern:(regexPattern) options:(0) |error|:(missing value)
set matches to (urlRegex's matchesInString:(theText) options:(0) range:({0, theText's |length|()}))
repeat with thisMatch in matches
	-- These are just examples. The number of groups depends on the regex pattern.
	-- The groups are numbered in the order of their leftmost "(" metacharacter.
	set fullMatchRange to thisMatch's range() -- Or thisMatch's rangeAtIndex:(0)
	set firstGroupRange to (thisMatch's rangeAtIndex:(1))
	set secondGroupRange to (thisMatch's rangeAtIndex:(2))
	-- Etc.
end repeat

Does this help?

1 Like

For me, it’s always helpful to have a working example. Using the approach suggested by Nigel (which is the one I would use):

use framework "Foundation"
use scripting additions

set theString to "1 11 111 2 22 222"
set theString to current application's NSString's stringWithString:theString
set thePattern to "\\d{3}" --three consecutive digits
set theRegex to current application's NSRegularExpression's regularExpressionWithPattern:thePattern options:0 |error|:(missing value)
set regexResults to theRegex's matchesInString:theString options:0 range:{location:0, |length|:theString's |length|()}
set theRanges to (regexResults's valueForKey:"range") as list -->{{location:5, |length|:3}, {location:14, |length|:3}} --a list of records

--Display location and length for testing only
repeat with aRange in theRanges
	set theLocation to location of aRange
	set theLength to |length| of aRange
	display dialog "Match Location: " & theLocation & linefeed & "Match Length: " & theLength
end repeat

Hi Adrian.* Welcome to MacScripter.

* The post to which this is a reply was subsequently reposted in German and with a link to a gambling site. The user and post have therefore been deleted from this forum.

That’s a good point about lists and records. For my own part, I’m not clear at this stage whether Daniel wants the ranges for their own sakes or to use to extract the matched substrings from theText using something like set matchedText to theText’s substringWithRange:(thisRange). In the latter case, ranges as lists, records, or references from repeat with … in … should all work.

Daniel’s script excerpt seems to be intended to extract a URL or URLs from some HTML text, but I’ve not been able to decide from the pattern if he wants URLs with particular things in them and whether or not they’re expected to be intact in the text. If he just wants any URLs that are in the text, it may be possible to avoid the use of regex and ranges altogether:

use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"

set exampleText to current application's class "NSString"'s stringWithString:("The URL of this page is \"https://www.macscripter.net/t/how-to-navigate-the-return-values-from-calls-to-cocoa-foundation-framework/78338\" and that of the second post in it is \"https://www.macscripter.net/t/how-to-navigate-the-return-values-from-calls-to-cocoa-foundation-framework/78338/2\".")
set URLDetector to current application's class "NSDataDetector"'s dataDetectorWithTypes:(current application's NSTextCheckingTypeLink) |error|:(missing value)
set URLMatches to URLDetector's matchesInString:(exampleText) options:(0) range:({0, exampleText's |length|()})
set NSURLs to URLMatches's valueForKey:("URL")
-- Or:
set URLStrings to (URLMatches's valueForKeyPath:("URL.absoluteString")) -- as list
1 Like

What I have to iterate over is a NSArray of NSRanges. I got it on how to iterate the NSArray. Now I don’t know how to access the members of each NSRange struct. Here is the code I have now :

	set matchRanges to (urlRegex's matchesInString:(theText) options:(0) range:({0, theText's |length|()}))'s valueForKey:("range")
	set matchRangesCount to count of matchRanges
	
	repeat with idx from 1 to matchRangesCount
		set element to (matchRanges's objectAtIndex:idx)
		set position to location of element
		set theSize to length of element
	end repeat

I get an error trying to access the location property of the NSArray element which is a NSRange.
Thanks,
Regards

ASObjC indices are 0-based, not 1-based as in AppleScript. So when using objectAtIndex:, the index range has to be from 0 to (matchRangesCount - 1) rather than from 1 to matchRangesCount.

When getting the properties of an ASObjC object, its necessary to use 's rather than of to denote possession. Also, the property labels are generally written followed by empty parentheses (eg. location()) when the properties are being accessed. Also, since length is an AppleScript keyword, it has to be written between vertical bars (ie. |length|) when it’s intended as a record or NSRange label. However, even these points don’t appear to fix the problem here. It seems to be necessary to coerce the NSRange to an AppleScript record and get the properties of that:

set matchRangesCount to matchRanges's |count|()
repeat with idx from 0 to (matchRangesCount - 1)
	set element to (matchRanges's objectAtIndex:idx) as record
	set position to element's location
	set theSize to element's |length|
end repeat

Or of course:

set matchRanges to matchRanges as list -- This also coerces the array's contents to AppleScript objects. Records in this case.
set matchRangesCount to (count matchRanges)
repeat with idx from 1 to matchRangesCount
	set element to item idx of matchRanges
	set position to element's location
	set theSize to element's |length|
end repeat

Nigel. This is at the far boundary of my ASObjC knowledge, but can this coercion be avoided by use of the rangeValue property? Perhaps the coercion takes place under-the-hood and there’s no difference. I learned of the rangeValue property from Google AI and implemented it in my example script from above.

use framework "Foundation"
use scripting additions

set theString to "1 22 333 4444 555"
set theString to current application's NSString's stringWithString:theString
set thePattern to "\\d{3,4}" --3 or 4 consecutive digits
set theRegex to current application's NSRegularExpression's regularExpressionWithPattern:thePattern options:0 |error|:(missing value)
set regexResults to theRegex's matchesInString:theString options:0 range:{location:0, |length|:theString's |length|()}
set theRanges to (regexResults's valueForKey:"range")

--Display location and length for testing only
repeat with aRange in theRanges
	set theLocation to aRange's rangeValue()'s location()
	set theLength to aRange's rangeValue()'s |length|()
	display dialog "Match Location: " & theLocation & linefeed & "Match Length: " & theLength
end repeat

Hi peavine.

Thanks. I’ve not come across rangeValue before. The Xcode documentation has it as a property of NSValue, but isn’t clear about its purpose (on a quick reading). In the current situation, it does exactly the same as coercing a range to record. :thinking:

1 Like

Hello,
Thank you all for your explanations. I now know more of calling Cocoa APIs in Applescript than before.
I went the route of coercing each array item into a record and now the code works.
But I took notice of the other two alternatives :

  • coerce the whole NSArray into a list
  • rangeValue Property

Regards