是否有 Objective-c 正则表达式替换为回调/C# MatchEvaluator 等效项?
我有一个 C# 项目,打算移植到 Objective-C。根据我对 Obj-C 的了解,似乎存在各种令人困惑的正则表达式选项,但我看不到任何有关使用回调进行替换的方法。
我正在寻找相当于 C# MatchEvaluator 委托或 PHP 的 preg_replace_callback 的东西。我想在 C# 中做的一个例子是 -
// change input so each word is followed a number showing how many letters it has
string inputString = "Hello, how are you today ?";
Regex theRegex = new Regex(@"\w+");
string outputString = theRegex.Replace(inputString, delegate (Match thisMatch){
return thisMatch.Value + thisMatch.Value.Length;
});
// outputString is now 'Hello5, how3 are3 you3 today5 ?'
我怎样才能在 Objective-C 中做到这一点?在我的实际情况中,正则表达式同时具有前向断言和后向断言,因此不幸的是,任何涉及提前查找字符串然后进行一系列直接字符串替换的替代方案都不起作用。
I have a C# project I'm intending to port to Objective-C. From what I understand about Obj-C, it looks like there's a confusing variety of Regex options but I can't see anything about a way of doing a replace with callback.
I'm looking for something that is the equivalent of the C# MatchEvaluator delegate or PHP's preg_replace_callback. An example of what I want to do in C# is -
// change input so each word is followed a number showing how many letters it has
string inputString = "Hello, how are you today ?";
Regex theRegex = new Regex(@"\w+");
string outputString = theRegex.Replace(inputString, delegate (Match thisMatch){
return thisMatch.Value + thisMatch.Value.Length;
});
// outputString is now 'Hello5, how3 are3 you3 today5 ?'
How could I do this in Objective-C ? In my actual situation the Regex has both lookahead and lookbehind assertions in it though, so any alternative involving finding the strings in advance and then doing a series of straight string replaces won't work unfortunately.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Foundation 有一个 NSRegularExpression 类( iOS4 及更高版本),这可能对您有用。来自文档:
例如:
Foundation has a NSRegularExpression class (iOS4 and later), which may be useful to you. From the docs:
For example:
我修改了 atshum 的代码,使其更加灵活:
现在似乎可以工作(可能需要更多测试)
I modified atshum's code to make it a bit more flexible:
Seems to work for now (probably needs a bit more testing)