简体   繁体   English

从UITextView文本的特定单词中检测下划线

[英]Detect underscore from a particular word of a UITextView's text

I want to detect "_" from a particular word of a UITextView's text. 我想从UITextView文本的特定单词中检测到“ _”。
I already tried this : 我已经尝试过了

But this calculates the range of first underscore only. 但这仅计算第一个下划线的范围。

 NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:textView.text]; NSRange range=[textView.text rangeOfString:@"_"]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:range]; textView.attributedText=string; 

My output is coming like this 我的输出像这样

Tadeusz_Kościuszko was a military leader who became a national hero in Poland. Tadeusz_Kościuszko是一位军事领导人,后来成为波兰的民族英雄。 A poster for the Paris premiere of Jules_Massenet's 1910 opera Don_Quichotte. Jules_Massenet的1910年歌剧Don_Quichotte在巴黎首映的海报。

And I want something like this: 我想要这样的东西:

Tadeusz Kościuszko was a military leader who became a national hero in Poland. TadeuszKościuszko是一位军事领导人,后来成为波兰的民族英雄。 A poster for the Paris premiere of Jules Massenet's 1910 opera Don Quichotte. 朱尔斯·马斯奈(Jules Massenet)1910年的歌剧《唐吉cho德》的巴黎首映海报。

Also I want to clear color the underscores just from the names. 我也想仅从名称中清除下划线。 Not from the other text of UITextView. 不是来自UITextView的其他文本。

I dont want to remove it from the whole text of UITextView but just from the particular words. 我不想从UITextView的整个文本中删除它,而只是从特定的单词中删除它。
Anyone having suggestions? 有人有建议吗?
Thanks. 谢谢。

textView.text = [textView.text stringByReplacingOccurrencesOfString:@"_" withString:@" "];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:textView.text];


NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(_)" options:kNilOptions error:nil];


NSRange range = NSMakeRange(0,string.length);

[regex enumerateMatchesInString:string options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

    NSRange subStringRange = [result rangeAtIndex:1];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:subStringRange];
}];

textView.attributedText=string;
NSString *str = @"This_is_a_string";

str = [str stringByReplacingOccurrencesOfString:@"_"
                                     withString:@" "];

// str = "This is a string"

More on NSString 有关NSString的更多信息

try this - 尝试这个 -

NSString *str   =   @"Tadeusz_Kościuszko was a military leader who became a national hero in Poland. A poster for the Paris premiere of Jules_Massenet's 1910 opera Don_Quichotte.";
    NSString *newStr    =   [str stringByReplacingOccurrencesOfString:@"_" withString:@" "];
    NSLog(@"NEW STR ::::: %@",newStr);

Found the workaround :) 找到了解决方法:)

NSString *strTemp = textView.text; NSString * strTemp = textView.text;

 NSMutableAttributedString *mutString = [[NSMutableAttributedString alloc]initWithString:strTemp]; NSString *substring = @"_"; NSRange searchRange = NSMakeRange(0,mutString.length); NSRange wholeTextRange = [strTemp rangeOfString:strTemp]; [mutString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:wholeTextRange]; NSRange foundRange; while (searchRange.location < mutString.length) { searchRange.length = mutString.length-searchRange.location; foundRange = [strTemp rangeOfString:substring options:nil range:searchRange]; if (foundRange.location != NSNotFound) { // found an occurrence of the substring! do stuff here [mutString addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:foundRange]; searchRange.location = foundRange.location+foundRange.length; } else { // no more substring to find [txtComment setAttributedText:mutString]; break; } } 

If you want to selectively remove underscores you need to know the range of text from which you want to remove them. 如果要有选择地删除下划线,则需要知道要删除下划线的文本范围。

Then you can use a regular expression to get an array of ranges which match the underscore in that known range. 然后,您可以使用正则表达式获取与该已知范围内的下划线匹配的范围数组。

NSError *error;
NSRegularExpression *regex =  [NSRegularExpression regularExpressionWithPattern:@"_" options:0 error:&error];
NSArray *matchingRangesInSelectedRange = [regex matchesInString:yourString options:0 range:knownRangeToCheckForMatches];

You can then iterate over the ranges in the array and do whatever changes you wish. 然后,您可以遍历数组中的范围,并进行所需的任何更改。

If you know which strings should not be cleaned or which that should not be cleaned you could do something like this: 如果你知道哪些字符串不应该被清理或者应该被清洗,你可以做这样的事情:

NSString *stringWithUnderScore = @"A rather long text with some_odd_underscores but also names like André_Franquin & Albert_Uderzo";
NSSet *stringsThatShouldKeepUnderscore = [NSSet setWithObjects:@"some_odd_underscores", nil];
NSArray *singleStrings = [stringWithUnderScore componentsSeparatedByString:@" "];
NSMutableString *newCompleteString = [[NSMutableString alloc] init];

for (NSString *singleString in singleStrings) {
        if (![stringsThatShouldKeepUnderscore containsObject:singleString]){
            NSString *fixedString = [singleString stringByReplacingOccurrencesOfString:@"_" withString:@" "];
            [newCompleteString appendString: fixedString];
        } else{
            [newCompleteString appendString:singleString];
        }
        [newCompleteString appendString:@" "];
    }

NSLog(@"new string:%@",newCompleteString);

Edit: If you do not have this information you could try to make some kind of parser checking if each of the strings separated by "_" have capital-letters, indicating a name. 编辑:如果您没有此信息,则可以尝试进行某种解析器检查,以“ _”分隔的每个字符串是否都有大写字母,表示名称。 Not fail-safe, but without knowledge about the text I can't really see any better option. 不是故障安全的,但是如果没有关于文本的知识,我真的看不到任何更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM