Skip to content

Instantly share code, notes, and snippets.

@adriannier
Last active December 23, 2017 09:51
Show Gist options
  • Save adriannier/33145380fe34333b995384415c952d72 to your computer and use it in GitHub Desktop.
Save adriannier/33145380fe34333b995384415c952d72 to your computer and use it in GitHub Desktop.
use framework "Foundation"
use scripting additions
set thePatterns to "(r\\s*\\d\\s*\\d\\s*[-\\s]*\\d\\s*\\d\\s*\\d\\s*\\d\\s*\\d)"
set theStrings to "R17-11517 r17-11518 r17-11519 R17-11518 R17-11519"
repeat 7 times
set thePatterns to thePatterns & return & thePatterns
set theStrings to theStrings & return & theStrings
end repeat
set startDate to current date
set theResult to matchesForPatternsAndStrings(thePatterns, theStrings)
log "Duration: " & ((current date) - startDate) & "s"
log "Processed " & (count of paragraphs of thePatterns) * (count of paragraphs of theStrings) & " regular expressions"
log "Result length: " & length of theResult & " characters"
-- Functions
on matchesForPatternsAndStrings(thePatterns, theStrings)
set thePatterns to str(thePatterns)
set theStrings to str(theStrings)
set thePatterns to thePatterns's componentsSeparatedByString:return
set theStrings to theStrings's componentsSeparatedByString:return
set allMatches to current application's NSMutableArray's array
repeat with i from 1 to count of theStrings
set allMatchesForThisLine to current application's NSMutableArray's array
repeat with j from 1 to count of thePatterns
set matchesForThisPattern to matchesForPatternAndString(item j of thePatterns, item i of theStrings)
(allMatchesForThisLine's addObjectsFromArray:matchesForThisPattern)
end repeat
(allMatches's addObject:(allMatchesForThisLine's componentsJoinedByString:"<DELIMITER>"))
end repeat
return (allMatches's componentsJoinedByString:return) as text
end matchesForPatternsAndStrings
on matchesForPatternAndString(aPattern, aString)
set regEx to current application's NSRegularExpression's regularExpressionWithPattern:aPattern options:1 |error|:(null)
set aRange to current application's NSMakeRange(0, aString's |length|())
set allMatches to regEx's matchesInString:aString options:0 range:aRange
set allMatchedStrings to current application's NSMutableArray's array
repeat with i from 1 to count of allMatches
(allMatchedStrings's addObject:(aString's substringWithRange:((item i of allMatches)'s rangeAtIndex:1)))
end repeat
return allMatchedStrings
end matchesForPatternAndString
on str(aString)
return current application's NSString's stringWithString:aString
end str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment