views:

155

answers:

2

I am using the GTMRegex class from the Google toolbox for mac (in a Cocoa / Objective-C) app:

http://code.google.com/p/google-toolbox-for-mac/

I need to do a match and replace of a 3 word phrase in a string. I know the 2nd and 3rd words of the phrase, but the first word is unknown.

So, if I had:

lorem BIFF BAM BOO ipsem

and

lorem BEEP BAM BOO ipsem

I would watch to match both (BEEP BAM BOO) and (BIFF BAM BOO). I then want to wrap them in bold HTML tags.

Here is what I have:

GTMRegex *requiredHeroRegex = [GTMRegex regexWithPattern:@"(\\([A-Z][A-Z0-9]*)\\b Hero Required)" options:kGTMRegexOptionSupressNewlineSupport|kGTMRegexOptionIgnoreCase];
out = [requiredHeroRegex stringByReplacingMatchesInString:out withReplacement:@"<b>\\1</b>"];

However, this is not working. basically, I cant figure out how to match the first word when I dont know it.

Anyone know the RegEx to do this?

Update:

GTRegEx uses POSIX 1003.2 Regular Expresions, so the solution is:

GTMRegex *requiredHeroRegex = [GTMRegex regexWithPattern:@"([[:<:]][A-Z][A-Z0-9]*[[:>:]])( Hero Required)" options:kGTMRegexOptionSupressNewlineSupport|kGTMRegexOptionIgnoreCase];
out = [requiredHeroRegex stringByReplacingMatchesInString:out withReplacement:@"<b>\\1\\2</b>"];

Note the crazy syntax for the word boundaries.

+1  A: 

You should use " .*? Hero Required", however, it will not catch phrase if it is the start of the sentence. For both cases use "( .*? Hero Required|^.*? Hero Required)".

Am
nongreedy regex.
Dyno Fu
Unfortunately, neither of those match anything.
mikechambers
i verified it with regexbuddy, so i assume the problem is in the code, not the regex part, and i don't know cocoa...
Am
Or it could be that that syntax just doesnt work with GTMRegex.
mikechambers
GTRegEx uses POSIX 1003.2 Regular Expresion. I posted the solution in the original message.
mikechambers
@mikechambers post it as an answer and accept it so that this question will appear solved in the listings.
Amarghosh
+1  A: 

Replace \b([a-z][a-z0-9]*)( second third) with <b>\1</b>\2

Amarghosh
That also does not match anything.
mikechambers