Counting specific characters

Hi, I hope you guys can help with this. I have a line of text just like this:

MND8QWND8ASNDISND09AMWWWMSOAIDSNDN

I would like to add this to my applescript to count how many W in it. in this case the result should be 4

any idea will help!

thank you for your time!

Brian

set theText to "MND8QWND8ASNDISND09AMWWWMSOAIDSNDNw"
considering case
	set howMany to (count my decoupe(theText, "W")) - 1
end considering

#=====

on decoupe(t, d)
	local oTIDs, l
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set l to text items of t
	set AppleScript's text item delimiters to oTIDs
	return l
end decoupe

#=====

As is the script count the uppercase W but not the lowercase ones.
If you want to count both case, disable the considering case and end considering instructions.
I put them in the caller script because I dislike to make changes in my standard handlers.

Yvan KOENIG (VALLAURIS, France) vendredi 20 mars 2015 23:00:13

Thank you! works great. but I need more help :frowning: how can I count a groupo of characters. the idea is to know hay many numbers area in the text and how many alphabet characters :frowning:

I think I found a very elegant solution:


set theText to characters of "abc23er55"
set Y to 0
log theText
repeat with i from 1 to count of items in theText
	set X to item i of theText
	if X is in "1234567890" then
		set Y to Y + 1
	end if
end repeat
log Y

Thank you all for your time!

You can use multiple text items (list of strings or characters) and still count them as in Yvanโ€™s example:

set theText to "abc23er55"
set oldTIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
set nrOfDigits to (count (text items of theText)) - 1
set AppleScript's text item delimiters to oldTIDs
return nrOfDigits

Hey Brian,

Iโ€™d use the Satimage.osax and regex.


set _text to "MND8QWND8ASNDISND09AMWWWMSOAIDSNDN"

try
	set countOfNumbers to length of (find text "\\d" in _text with regexp, all occurrences and string result)
on error
	set countOfNumbers to false
end try

try
	set countOfLetters to length of (find text "[[:alpha:]]" in _text with regexp, all occurrences and string result)
on error
	set countOfLetters to false
end try

Thank you!!! :slight_smile: