-3

I have a string that sometimes contains strings like: @"[id123123|Some Name]" What I have to do, is to simply replace it to "Some Name"

For example I have string: Some text lalala blabla [id123|Some Name] bla bla bla

And I need to get: Some text lalala blabla Some Name bla bla bla

The question is how to? My mind tells me that I can do this with NSRegularExpression

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Didar1994
  • 9
  • 5
  • You don't need a regular expression for this. Simply split the string on the vertical bar and remove the trailing close bracket. – rmaddy Apr 27 '15 at 14:33
  • Is there a chance that the rest of the text contains either **[**, or **]** or **|** ? If not, then you probably don't need a regex but simply split the string and rebuild it – Gil Sand Apr 27 '15 at 14:37

3 Answers3

1

Look into stringByReplacingOccurrencesOfString:withString:options:range:. The options: allow the search string to be a regular expression pattern.

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

Not an Objective C person, but judging from this previous SO post, you could use a regex like so:

NSString *regexToReplaceRawLinks = @"\\[.+?\\|(.+?)\\]";   

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceRawLinks
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSString *string = @"[id123|Some Name]";

NSString *modifiedString = [regex stringByReplacingMatchesInString:string
                                                           options:0
                                                             range:NSMakeRange(0, [string length])
                                                      withTemplate:@"$1"];

This should match the string you are using and place the name in a group. You then replace the entire string [id123|Some Name] with Some Name.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
0

Regex101

(\[[^|]+|([^\]]+]))

Description

\[ matches the character [ literally
[^|]+ match a single character not present in the list below
    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
| the literal character |
\| matches the character | literally
1st Capturing group ([^\]]+])
    [^\]]+ match a single character not present in the list below
        Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
    \] matches the character ] literally
    ] matches the character ] literally

In capture group 1 is the thing you want to replace with what is in capture group 2. enjoy.

abc123
  • 17,855
  • 7
  • 52
  • 82