搜索子字符串(NSString)
搜索 ## $$ 括起来的子字符串的最佳方法是什么。例如,我有一些这样的文本:
Lorem ##ipsum$$ dolor sat amet, ##consectetur$$ adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。 Ut enim ad minim veniam, quis nostrud exeritation ullamco labouris nisi ut aliquip ex ea commodo consequat.
我想要获取单词 ipsum 和 consectetur。我知道我可以执行 NSString rangeofsubstring 方法,但是有更好的方法吗?基本上,找到一个被另外两个字符串包围的字符串? 谢谢
What's the best way to search for substring that are enclosed by ## $$. So for example, I have some text like this:
Lorem ##ipsum$$ dolor sit amet, ##consectetur$$ adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
I want to get the words ipsum and consectetur. I know I can do NSString rangeofsubstring method, but is there a better way to do this? Basically, find a string enclosed by 2 other strings?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
NSRegularExpression
(警告:仅限 iOS4+)使用正则表达式模式(通常如@"##.*$$"
)匹配您的子字符串。然后很容易迭代结果匹配(我的首选方法是使用枚举块,因为我们不是 iOS4 :-)):
注意:如果您需要支持 iOS4 之前的版本,您可以检查 < a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html" rel="nofollow">
NSPredicate
但它的灵活性要差得多(...我猜对于 iOS4 之前的版本,使用 rangeOfSubstring 可能是最好的选择,因为 NSPredicate 只会告诉如果字符串匹配但不允许您获取子字符串...)Your can use
NSRegularExpression
(warning: iOS4+ only) to match your substrings using a RegEx pattern (like@"##.*$$"
typically).It is then really easy to iterate thru the resulting matches (my preferred way is using an enumeration block, as we are un iOS4 :-)):
Note: If you need to support pre-iOS4 versions, you can check
NSPredicate
but it is much less flexible (... and I guess that for pre-iOS4, using rangeOfSubstring is probably the best choice anyway as NSPredicate will only tell you if a string is matching but won't allow you to get the substring...)遍历字符串字符,搜索“##”,然后搜索最近的“$$”。
Iterate through string characters, searching for '##', and after that search for nearest '$$'.