我遇到了一个奇怪的问题。在我的UI-textview中我详细说明了文字,我想突出显示/用特定单词开头的某一行或颜色。到目前为止,我能够找到起始单词的位置但不是能够找到该行和段落的结尾。问题是新行(\ n)无法识别,因为我已经尝试过了。
任何人都可以帮我找到解决方案。这是代码
NSArray *matches = [regex matchesInString:self.textfiled.text options:0 range:NSMakeRange(0, self.textfiled.text.length)];
for (NSTextCheckingResult *match in matches) {
NSString *string =self.textfiled.text;
NSRange wordRange = [match rangeAtIndex:0];
unsigned long lock=0;
unsigned long i=0;
[stirng replaceCharactersInRange:wordRange withString:@"\nདཔེར་ན། "];
unsigned long length = [string length];
unsigned long paraStart = wordRange.length,paraEnd =0,contentsEnd =0;
NSMutableArray *array = [NSMutableArray array];
NSRange currentRange;
for( i=0;![[self.textfiled.text substringWithRange:NSMakeRange(wordRange.location+i+1,1)] isEqualToString:@" "];i++)
{
NSLog(@"\n %lu------------>",i);
lock=i;
}
NSLog(@"\n %lu------------>",lock);
NSRange range = NSMakeRange(wordRange.location,wordRange.length);
NSString *str = [self.textfiled.text substringWithRange:range];
NSLog(@"\n%lu--------",[str length]);
NSRange wordRanged1 = NSMakeRange(wordRange.location, 7+7);
[stirng addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:22/255.0f green:123/225.0f blue:108/255.0f alpha:1.0f] range:wordRanged1];
}
答案 0 :(得分:0)
根据您的代码的灵感,我创建了一个类似的解决方案,在给定匹配单词的起始字符的情况下,找到行结束和段落结束。段落以\n\n
分隔,行以\n
结尾。文本字段的结尾可能需要作为特殊情况处理。
请注意,.*
将与给定正则表达式选项的行尾匹配。通过找到匹配的\n\n
来找到段落结尾。
self.myText = @"hello world\n\nthis is a test\nsingle line\n\n";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"hello.*"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *matches = [regex matchesInString:self.myText options:0 range:NSMakeRange(0, self.myText.length)];
for (NSTextCheckingResult *match in matches) {
NSRange lineRange = [match rangeAtIndex:0];
NSLog(@"match start is %lu", lineRange.location);
NSLog(@"line end is %lu", lineRange.location + lineRange.length);
// Find paragraph ends:
NSInteger i = lineRange.location;
unichar lineSeparator = 0x2028;
while (i < self.myText.length - 1) {
// Case where string uses \n\n to denote a paragraph:
NSString *subString = [self.myText substringWithRange:NSMakeRange(i, 2)];
if ( [subString isEqualToString:@"\n\n"] ) {
NSLog(@"found paragraph end at %ld", (long)i);
}
// Case where text view uses line separator characters:
if ([subString characterAtIndex:0] == lineSeparator && [subString characterAtIndex:1] == lineSeparator) {
NSLog(@"found paragraph end at %ld", (long)i);
}
i++;
}
}
在我的样本中,我得到了
match start is 0
line end is 11
found paragraph end at 11
found paragraph end at 39
我已经创建了一个可视化结果的小指南:
hello world++this is a test+single line++
01234567891111111111222222222233333333334
0123456789012345678901234567890
这可以适应一个独立的功能,应该提供你正在寻找的那种结果。