[英]Get NSRange from NSRegularExpression match
I have an array which contains NSRange
elements. 我有一个包含
NSRange
元素的数组。
Now i can get the last range element of the array using [resultArray lastObject]
. 现在我可以使用
[resultArray lastObject]
获取数组的最后一个range元素。
When i access the last element, It returns some unknown object. 当我访问最后一个元素时,它返回一些未知对象。 (Which means Unknown class)
(这意味着未知类)
Now i want to cast the object into NSRange
. 现在我想将对象转换为
NSRange
。 How to do it? 怎么做?
My code is: 我的代码是:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:paraStartRegEx options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regex matchesInString:content options:0 range:NSMakeRange(0, [content length])];
NSObject *obj = [matches lastObject];
How can I convert this object to NSRange
? 如何将此对象转换为
NSRange
?
If you had read the documentation, you would have noticed that the matchesInString:options:range:
method of NSRegularExpression
returns an NSArray
of NSTextCheckingResult
objects, not NSRange
s, so it's no wonder that you couldn't get them out directly. 如果您已经阅读文档,你会注意到
matchesInString:options:range:
方法NSRegularExpression
返回NSArray
的NSTextCheckingResult
对象,而不是 NSRange
S,所以这也难怪,你不能直接把他们救出来。
Additionally (and you should remember this for the future, as it is an important distinction), NSRange
is a C struct
, not an Objective-C object. 另外(你应该记住未来,因为它是一个重要的区别),
NSRange
是一个C struct
,而不是一个Objective-C对象。 This means that it cannot be directly stored in NSArray
s or other Objective-C object containers. 这意味着它不能直接存储在
NSArray
或其他Objective-C对象容器中。 NSArray
, NSDictionary
, and other Objective-C classes that are used for storing objects can only store objects of Objective-C types , ie, objects that are an instance of a Class
and can have messages sent to them with [object method]
. NSArray
, NSDictionary
和其他用于存储对象的Objective-C类只能存储Objective-C类型的对象,即作为Class
实例的对象,并且可以使用[object method]
将消息发送给它们。
Now to get back to your question, the array you are getting from matchesInString:options:range:
contains NSTextCheckingResult
objects, which contain a lot more information than just the range of the match, so you can't just cast them to an NSRange
; 现在回到你的问题,你从
matchesInString:options:range:
得到的数组matchesInString:options:range:
包含NSTextCheckingResult
对象,它们包含的信息不仅仅是匹配的范围,所以你不能只将它们转换为NSRange
; you need to access the range
property of the object to get what you want: 您需要访问对象的
range
属性才能获得所需内容:
NSTextCheckingResult *result = [matches lastObject];
NSRange range = [result range];
NSRange is a C struct. NSRange是一个C结构。
NSArray does not hold C types, only objects. NSArray不包含C类型,只包含对象。
NSRegularExpression returns a match NSArray that contains objects of NSTextCheckingResult type. NSRegularExpression返回包含NSTextCheckingResult类型对象的匹配NSArray 。
NSTextCheckingResult has a range property that returns the range of a match. NSTextCheckingResult有一个范围属性,可返回匹配范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.