AppleScript – how to search a list for items containing numbers

applescript

I'm writing an AppleScript which contains a list of items that are mixed between text and numbers. I'd like to filter this list to only the items containing numbers.

I haven't been able to figure this out on my own and so far haven't been able to find any helpful suggestions online.

Here's my list:

{"table", "s01e01", "nam", "aces", "linear", "20160430", "01", "textless", "3840x2160", "000011", "jpg"}

And I only want the search to return these:

{"s01e01", "20160430", "01", "3840x2160", "000011"}

For the sake of this post, let's say the list is stored in myList.

I've tried:

set numberItems to items of myList which contain integers

but that's a big no go!

Best Answer

This doesn't seem like a terribly efficient way to do it, but I think that's an AppleScript issue rather than my lack of creativity (I might be wrong):

    set mylist to {"table", "s01e01", "nam", "aces", "linear", "20160430", "01", "textless", "3840x2160", "000011", "jpg"}

    repeat with str in mylist
        set str to the contents of str

        repeat with i from 0 to 9
            if str contains i then
                set end of mylist to str
                exit repeat
            end if
        end repeat

        set mylist to the rest of mylist
    end repeat

    return mylist

You could do it much more gracefully using a bit of shell script:

    set mylist to {"table", "s01e01", "nam", "aces", "linear", "20160430", "01", "textless", "3840x2160", "000011", "jpg"}

    set the text item delimiters to space

    do shell script "grep -o '\\S*\\d\\S*' <<< " & the quoted form of (mylist as text)

    return the paragraphs of the result 

EDIT: I spoke a little too soon about my (lack of creativity), as I just came up with this slightly slicker method of doing it with AppleScript. In theory, it should be faster than the first method too:

    set mylist to {"table", "s01e01", "nam", "aces", "linear", "20160430", "01", "textless", "3840x2160", "000011", "jpg"}

    set the text item delimiters to {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

    repeat with str in mylist
        set str to the contents of str as text

        if str ≠ the text items of str as text then ¬
            set the end of mylist to str

        set mylist to the rest of mylist
    end repeat

    return mylist