简体   繁体   English

在RegEx标识的NSString中的某个点添加一个字符,是否有比所有后向引用更有效的方法?

[英]Adding a character at a certain point in a NSString identified by RegEx, is there a more efficient way to do it than ALL back references?

I want to take a URL like http://imgur.com/isodf99.jpg add the letter m right before the file extension. 我想采取像http://imgur.com/isodf99.jpg这样的网址,在文件扩展名之前添加字母m So that URL before becomes http://imgur.com/isodf99m.jpg . 所以之前的URL变成了http://imgur.com/isodf99m.jpg

I'm guessing the best way to identify that point would be via RegEx (I know I could just go back four places from the end, but that wouldn't work with .jpeg ) but I'm having trouble figuring out the best implementation of it. 我猜测识别这一点的最好方法是通过RegEx(我知道我可以从最后回到四个位置,但这对.jpeg不起作用)但是我在找出最好的实现时遇到了麻烦它的。 I'm confused how to say "find that string of random letters and numbers and add an m to the end of it". 我很困惑如何说“找到随机字母和数字的字符串并在其末尾添加一个m”。

My first reaction was to separate the portions of the URL into "before code", "code" and "after code" and save them as back references, then reconstruct them but add an m to the second back reference. 我的第一反应是将URL的各部分分成“在代码之前”,“代码”和“在代码之后”并将它们保存为后引用,然后重构它们,但是将m添加到第二个后引用。

So, this screenshot for example illustrates it: 因此,这个屏幕截图举例说明了这一点:

在此输入图像描述

(The app is Patterns by the way, always get asked that.) (该应用程序是模式顺便说一下,总是被问到。)

But I'm not sure that's the best way. 但我不确定这是最好的方式。 Is there a more straightforward way? 有更简单的方法吗?

If you don't insist on using regular expressions, this would work: 如果您不坚持使用正则表达式,这将起作用:

NSString *url = @"http://imgur.com/isodf99.jpg";
url = [[[url stringByDeletingPathExtension]
        stringByAppendingString:@"m"]
       stringByAppendingPathExtension:[url pathExtension]];
NSLog(@"%@", url);
// http://imgur.com/isodf99m.jpg

Or, if you work with NSURL instead of NSString: 或者,如果您使用NSURL而不是NSString:

NSURL *url = [NSURL URLWithString:@"http://imgur.com/isodf99.jpg"];

// Extract the path:
NSString *path = [url path];

// Insert "m" before path extension:
path = [[[path stringByDeletingPathExtension]
        stringByAppendingString:@"m"]
        stringByAppendingPathExtension:[path pathExtension]];

// Rebuild URL with new path:
url = [[NSURL alloc] initWithScheme:[url scheme] host:[url host] path:path];

But if you prefer a regular expression: 如果您更喜欢正则表达式:

NSString *url = @"http://imgur.com/isodf99.jpeg";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\.[^.]*)$"
                                                                       options:0 error:NULL];
url = [regex stringByReplacingMatchesInString:url
                                      options:0
                                        range:NSMakeRange(0, [url length])
                                 withTemplate:@"m$1"];

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

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