-1

I need to write a regular expression to replace string @<Number|Text>@ to Text in my iOS application.

@<Number|Text>@

e.g.

  • @<12|abcd>@ will be abcd
  • @<1|I am a good boy>>>>>@ will be I am a good boy>>>>
  • @<a|abcd>@ no change, because the first part is not numeric
  • @<0|god bless me@>>@ will be god bless me@>
  • @<01212|I love you!>@ Do you love me? @<0222| No, I love your sister>@ will be I love you! Do you love me? No, I love your sister

I am not familiar with regular expression, can someone help me?

What I have tried:
@<(\d{1,})\|([\S]+)>@
@<(\d{1,})\|([\S\s]+)>@

P.S. Any other solution is welcome. Actually what I want to do is replace @<ID|NAME>@ to @NAME and make @NAME as clickable(I use TTTAttributedLabel), the url will be goto://ID

eddie
  • 1,252
  • 3
  • 15
  • 20
ZYiOS
  • 5,204
  • 3
  • 39
  • 45
  • 1
    You need to research and try something, then add your attempt to the question if it doesn't work and explain what it does wrong – Wain Jan 04 '16 at 11:56
  • @Wain thanks, I actually tried something like: "@<(\d{1,})\|([\S ]+)>@", but failed. – ZYiOS Jan 04 '16 at 13:18
  • why has it to be a RegEx-based solution? A parser based on NSScanner could be easily coded and performant. – vikingosegundo Jan 04 '16 at 13:29

1 Answers1

2

The regular expression you are searching for is @<\\d+\\|(.*?)>@. And the replacement template is $1.

Breaking down the regular expression:

  • @< will match the prefix of the expression
  • \\d+ will match at least one digit
  • \\| will match the | character
  • (.*?) will match any character up to the next part of the regular expression (>@); the parentheses create a sub-pattern, which gets mapped to $1 in the replacement string
  • finally, >@ will match the end of the pattern

The ? addresses the greediness of the *quantifier, without it * would not work for the last example, as it will match anything between the first @< and the last >@.

Cristik
  • 30,989
  • 25
  • 91
  • 127