My friends and family are under attack in Ukraine. Donate to protect them directly or help international organizations.

lastIndexOf with RegEx?

February 6th, 2009

I was quite surprised that Flex did not have a way to get the index of the LAST matching substring. I want get the index of a word's first character based on the cursor's position (I'm working with the text property of a UITextField).

To achieve that I'm getting all text in front of that word: text.substring(0, cursorPosition). Then, I simply want to search for the last non-word character (\W), if there is any. That way, I can have the index of the first character of the word.

So to get the last non-word character, I can't use lastIndexOf() because it doesn't support RegEx, I can't use match() because it returns an array of substrings instead of indices and I can't use search() because it returns the first index, not the last.

There is a way around the missing "searchLast()" and "searchAll()" functions.

I get a substring before the cursorPosition: text.substring(0, cursorPosition)
I loop through all characters backwards and check if it's a non-word char.
Once I find it, I record the index at which it was found.

There might be other ways to get the beginning of a word based on cursor position, so don't hesitate to share them. I really hope that the next SDK version will come with searchLast() and searchAll() functions.

Previous: Flex Randomness Next: Flex 3D and Wiimote