3

I have a string like this:

NSString* msg = @"Hello this is a new message to @[123:Dr Zoidberg] and his nippers";

And I want to use -stringByReplacingMatchesInString:options:range:withTemplate: to convert this pattern to:

NSString* msg = @"Hello this is a new message to Dr Zoidberg and his nippers"; 

This is what I have so far:

NSString* msg = @"Hello this is a new message to @[123:Dr Zoidberg] and his nippers";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: @"????"
                                                                       options: NSRegularExpressionCaseInsensitive
                                                                         error: nil];

NSString* plainText = [regex stringByReplacingMatchesInString: msg
                                                      options: 0
                                                        range: NSMakeRange(0, [msg length])
                                                 withTemplate: @"$2"];

Can anyone help me with the @"????" pattern?

Paul de Lange
  • 10,613
  • 10
  • 41
  • 56

3 Answers3

2

This was the pattern I was after: @(.*?):(.*?)]. Thanks go to this question.

Community
  • 1
  • 1
Paul de Lange
  • 10,613
  • 10
  • 41
  • 56
0

Try replacing

@\[\d+:(.+?)\]

with the \1 group

Explanation:

Match @ followed by [, then any number of digits followed by a comma. From this point get the text until you find the closing square bracket.

If there can be any kind of whitespace between the digits and the : you can use this one

@\[\d+\t*:(.+?)\]
Gabber
  • 5,152
  • 6
  • 35
  • 49
  • It works on notepad++. What does it match / doesn't it match? It looks a lot like the one mmdemirbas commented, maybe the problem is the square bracket at the beginning – Gabber Aug 27 '12 at 13:55
  • Uhu, can there be a space (or any indentation character) between `123` and `:`? if so you can write it in this fashion `@\[\d+\t+?:(.+?)\]` – Gabber Aug 27 '12 at 13:58
  • the `?` means "don't be greedy with the +", in this case in fact you can omit it (my mistake, I'll edit the answer) – Gabber Aug 27 '12 at 13:59
  • Think I understood: you must replace `withTemplate: @"$2"` with `withTemplate: @"$1"` telling to use the first replacing group, not the second – Gabber Aug 27 '12 at 14:06
0

Search for @\[123:(.*?)\] and replace with \1

mmdemirbas
  • 9,060
  • 5
  • 45
  • 53