我想用 REGEX 搜索下一个和上一个单词,我可以使用以下格式获取。
在这种情况下,我搜索了单词"" ,因此我可以获得"" 的下一个和上一个单词。我可以成功使用以下模式。
'\\b(?=(\\w+\\s+the|the\\s+\\w+)\\b)'
但是使用这种模式,我遇到的一个问题是,当搜索到的单词是第一页("引用"如果是下面的示例文本)或最后一个(&#34) ;附件"如果是以下示例文本),它将无法找到它。
示例文字
引用仲裁员在听证会附件之前应阅读的任何案件或其他法律材料
我也获得第一个和最后一个词,但使用不同的模式。 搜索词时的模式是第一页。
For First words
'\\b(?=($+cite|cite\\s+\\w+)\\b)'
最后一句话
'\\b(?=(\\w+\\s+attachments|attachments+$)\\b)'
我想要所有这三种可能性,单一模式天气词是第一个或最后一个或中间。
已经测试过改变组合,但没有成功。
任何人都可以帮助我以一种模式获取所有这些,就像它应该给下一个/前一个单词的结果一样吗?
答案 0 :(得分:2)
您可以使用此(\w+)?\s+cite(\s+\w+)?|cite\s+(\w+)?
以及(\w+)?\s*\bcite\b\s*(\w+)?
(假定cite
令牌作为示例字词)
示例字符串:
引用任何案件或其他法律材料引用仲裁员应在听证会附件之前阅读
匹配
请参阅DEMO
答案 1 :(得分:1)
我认为您可以使用以下使用可选捕获组的正则表达式捕获所有内容,无需使用替换:
(\w+)?\s*\b(cite)\b\s*(\w+)?
不要忘记在Objective C中使用双重转义斜杠。
#import <Foundation/Foundation.h>
#import <Foundation/NSTextCheckingResult.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSError *error = nil;
NSString *pattern = @"(\\w+)?\\s*\\bcite\\b\\s*(\\w+)?";
NSString *string = @"cite any cases or other legal materials cite that the arbitrator should read before the hearing attachments cite";
NSRange range = NSMakeRange(0, string.length);
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:range];
for (NSTextCheckingResult *match in matches) {
NSRange matchRange = [match range];
NSString *m = [string substringWithRange:matchRange];
NSLog(@"Matched string: %@", m);
}
[pool drain];
return 0;
}
输出:
2015-04-09 11:08:22.630 main[26] Matched string: cite any
2015-04-09 11:08:22.633 main[26] Matched string: materials cite that
2015-04-09 11:08:22.633 main[26] Matched string: attachments cite