I’m using iPhone SDK and need of assistance.
I have the following array of search terms:
f, f, last, m
And a string (the top numbers are just indexes for convenience):
0 10 21 30 45
firstname middlename lastname firstnameagain firstnomatch
Expected result ranges (location, length): (0, 1) (30, 1) (21, 4) (10, 1)
I would like to have a regular expression that matches all the search terms in the string but only if they are a prefix of a word. When the search term appears N times, it will match only the first N prefixes (In the example, “f” was entered twice thus the possible match at (45, 1) wasn’t returned).
I’ve tried to write many possible regular expressions and all have failed to match with proper results. I’ve came to the conclusion that the “\b” meta-character cannot be used because the string can contain non word characters adjacent to letters (“firstname#”, “?lastName”, …)
I’m not sure this is a job for a regex alone.
This could be accomplished with or without a regex, by exploding the string by spaces and then checking each string against a list of remaining prefixes.
You keep a list of prefixes as such:
And when you match against firstname, you remove the prefix that was found. In this case, you remove f:
When you match against firstnameagain, you remove f again, and no longer try to match f:
To perform the search, you could iterate through the array of search prefixes and use the NSString rangeOfString function to see if the search prefix is at the front. If you still want to use a regex, you can match against:
As you match prefixes, remove them from the array, then remake the regex.