mikechambers
mikechambers

Reputation: 3089

Match first word of a phrase in a String

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

Upvotes: 0

Views: 819

Answers (2)

Amarghosh
Amarghosh

Reputation: 59451

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

Upvotes: 1

Amirshk
Amirshk

Reputation: 8258

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)".

Upvotes: 1

Related Questions