匹配字符串中短语的第一个单词
我正在使用 Mac 版 Google 工具箱(在 Cocoa / Objective-C 中)应用程序中的 GTMRegex 类:
http://code.google.com/p/google-toolbox-for-mac/
我需要匹配并替换字符串中的 3 个单词短语。我知道该短语的第二个和第三个单词,但第一个单词未知。
所以,如果我有:
lorem BIFF BAM BOO ipsem
和
lorem BEEP BAM BOO ipsem
我会观察匹配 (BEEP BAM BOO) 和 (BIFF BAM BOO)。然后我想将它们包装在粗体 HTML 标签中。
这是我所拥有的:
GTMRegex *requiredHeroRegex = [GTMRegex regexWithPattern:@"(\\([A-Z][A-Z0-9]*)\\b Hero Required)" options:kGTMRegexOptionSupressNewlineSupport|kGTMRegexOptionIgnoreCase];
out = [requiredHeroRegex stringByReplacingMatchesInString:out withReplacement:@"<b>\\1</b>"];
但是,这不起作用。基本上,当我不知道第一个单词时,我不知道如何匹配它。
有人知道正则表达式可以做到这一点吗?
更新:
GTRegEx 使用 POSIX 1003.2 正则表达式,因此解决方案是:
GTMRegex *requiredHeroRegex = [GTMRegex regexWithPattern:@"([[:<:]][A-Z][A-Z0-9]*[[:>:]])( Hero Required)" options:kGTMRegexOptionSupressNewlineSupport|kGTMRegexOptionIgnoreCase];
out = [requiredHeroRegex stringByReplacingMatchesInString:out withReplacement:@"<b>\\1\\2</b>"];
注意单词边界的疯狂语法。
更新 2:这是 JavaScript 版本:
/(([A-Za-z]*?|[A-Za-z]*? [A-Za-z]*?)( Hero Required))/gm
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用
" .*? Hero required"
,但是,如果它是句子的开头,则不会捕获短语。对于这两种情况,请使用
“(.*?需要英雄|^.*?需要英雄)”
。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)"
.将
\b([az][a-z0-9]*)(第二个第三)
替换为\1\2
Replace
\b([a-z][a-z0-9]*)( second third)
with<b>\1</b>\2