Sunday, August 18, 2019

#1 2019-05-30 11:21:01 pm

akim
Member
Registered: 2010-04-04
Posts: 101

Extracting digits with Objective C

As Objective C identifies integers as decimal digit characters, it possible to extract integers from a string without using Objective C's inversion method.
Although the  following script  successfully extracts digits from a ten digit phone number, I want to write the script in a more concise fashion.

Applescript:

use framework "Foundation"
use scripting additions

set SourceText to "(123)456-7890"

# Create an NS String from the SourceText.
set SourceNSString to (current application's NSString's stringWithString:SourceText)

# Get all characters which are not digits 0 through 9.
set nonDigitCharacterSet to (current application's NSCharacterSet's decimalDigitCharacterSet's invertedSet())

# Extract components of the SourceText that are not included in the prior inversion, ie, that are in the set of characters representing digits 0 through 9.
set ExtractedNumberListsOfStrings to SourceNSString's componentsSeparatedByCharactersInSet:nonDigitCharacterSet

# Join the list of component strings using "" as the text item delimiter.
ExtractedNumberListsOfStrings's componentsJoinedByString:""

# Yields 1234567890

What other Applescript Objective C alternatives might provide a more concise method?

Offline

 

#2 2019-06-01 02:36:31 am

StefanK
Member
From:: St. Gallen, Switzerland
Registered: 2006-10-21
Posts: 11578
Website

Re: Extracting digits with Objective C

A more concise method is stringByReplacingOccurrencesOfString:options:range. You can remove all non-digit characters with Regular Expression

Applescript:

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

set SourceText to "(123)456-7890"

# Create an NS String from the SourceText.
set sourceNSString to (current application's NSString's stringWithString:SourceText)

# Remove all non-digit characters.
set theResult to sourceNSString's stringByReplacingOccurrencesOfString:"[^0-9]" withString:"" options:(current application's NSRegularExpressionSearch) range:{location:0, |length|:count SourceText}

# Yields 1234567890


regards

Stefan

Offline

 

#3 2019-06-01 11:09:14 am

akim
Member
Registered: 2010-04-04
Posts: 101

Re: Extracting digits with Objective C

Stefan,
Your demonstration of a conversion between Objective C and Objective C regex inversions and your  comparison has given me a better understanding of Objective C's method of substituting for Regex.
If I understand your method correctly, the use of Regex via Objective C allows a greater manipulation of a string using the combination of:
• stringByReplacingOccurrencesOfString method
• Regex inversion of the find expression
• replacement with ""
Thank you for your help.

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)