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.
Update 2 : Here is the JavaScript version:
/(([A-Za-z]*?|[A-Za-z]*? [A-Za-z]*?)( Hero Required))/gm