Re: Need help with RegularExpressions in AppleScript ObjC
Re: Need help with RegularExpressions in AppleScript ObjC
- Subject: Re: Need help with RegularExpressions in AppleScript ObjC
- From: Shane Stanley <email@hidden>
- Date: Fri, 8 Dec 2017 09:25:32 +1100
On 8 Dec 2017, at 7:11 am, Luc Naets <email@hidden> wrote:
>
> When running the following script I would expect to have 3 matches in
> theFinds but I only have 1.
> When using the same regex pattern in my old fashioned perl way I do have 3
> captured groups.
>
> What’s wrong then with this ObjC regex?
You're not getting any capture groups (other than 0) because you're not asking
for them. Try something like this:
on findPattern:thePattern inString:theString
set theOptions to ((NSRegularExpressionDotMatchesLineSeparators) as
integer) + ((NSRegularExpressionAnchorsMatchLines) as integer)
set theRegEx to NSRegularExpression's
regularExpressionWithPattern:thePattern options:theOptions |error|:(missing
value)
set theFinds to theRegEx's matchesInString:theString options:0
range:{location:0, |length|:length of theString}
set theFinds to theFinds as list
set theResult to {}
set theNSString to NSString's stringWithString:theString
repeat with aFind in theFinds
set theGroups to {}
repeat with i from 0 to (aFind's numberOfRanges()) - 1
set theRange to (aFind's rangeAtIndex:i)
set end of theGroups to (theNSString's
substringWithRange:theRange) as text
end repeat
set end of theResult to theGroups
end repeat
return theResult
end findPattern:inString:
Or better still, skip regular expressions altogether and parse your string as
the XML it is:
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
-- classes, constants, and enums used
property NSXMLDocument : a reference to current application's NSXMLDocument
property NSXMLNode : a reference to current application's NSXMLNode
property NSString : a reference to current application's NSString
set mDIV to "<div class=\"test\"><textarea id=\"22\">Albert</textarea></div>"
set {theDoc, theError} to NSXMLDocument's alloc()'s initWithXMLString:mDIV
options:0 |error|:(reference)
if theDoc is missing value then error theError's localizedDescription() as text
set theClass to (theDoc's rootElement()'s attributeForName:"class")'s
stringValue() as text
set textArea to (theDoc's rootElement()'s elementsForName:"textarea")'s
firstObject()
set theID to (textArea's attributeForName:"id")'s stringValue() as text
set textAreaString to textArea's stringValue() as text
--
Shane Stanley <email@hidden>
<www.macosxautomation.com/applescript/apps/>, <latenightsw.com>
_______________________________________________
Do not post admin requests to the list. They will be ignored.
applescriptobjc-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden