0

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
4

2 回答 2

1

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

于 2010-01-19T07:48:46.117 回答
1

您应该使用" .*? Hero Required",但是,如果它是句子的开头,它将无法捕捉短语。对于这两种情况,使用"( .*? Hero Required|^.*? Hero Required)".

于 2010-01-19T07:44:30.843 回答