Home > front end >  How do I write this Objective-C code into AppleScript?
How do I write this Objective-C code into AppleScript?

Time:09-21

I want to implement this Objective-C example to be used in AppleScript but I don't know how to do it.

NSTextCheckingResult *match = [regex firstMatchInString:string
                                            options:0
                                              range:NSMakeRange(0, [string length])];
if (match) {
    NSRange matchRange = [match range];
    NSRange firstHalfRange = [match rangeAtIndex:1];
    NSRange secondHalfRange = [match rangeAtIndex:2];
 }

Here's what I've got so far and I don't know how to proceed

set theString to "hello world"
set theString2 to "\\w "

set firstMatch to (regex's firstMatchInString:theString options:0 range:{location:0, |length|:(count theString)}) as list  -- do I need to coerce to list?
-- below is obviously wrong
if firstMatch is not missing value then 
    set matchRange = current application's NSRange's range
end if 

CodePudding user response:

Exists only one range (with index=0) in this case. So, do not request for range at index > 0

use AppleScript version "2.4" -- Yosemite or later
use framework "Foundation"
use scripting additions

set searchString to "hello world"
set regexString to "\\w "

set anNSString to current application's NSString's stringWithString:searchString
set stringLength to anNSString's |length|()
set theRegex to current application's NSRegularExpression's regularExpressionWithPattern:regexString options:0 |error|:(missing value)

set match to theRegex's firstMatchInString:anNSString options:0 range:{0, stringLength}

if match is not missing value then
    set matchRange to match's numberOfRanges()
    --> 1, so exists only one range, with index=0
    set matchRange to match's rangeAtIndex:0
end if

set firstMatchString to text ((matchRange's location)   1) thru ((matchRange's location)   (matchRange's |length|)) of searchString
  • Related