ZYiOS ZYiOS - 3 months ago 8
Swift Question

RegularExpression to detect below text format: @<10|asdffdfs>@

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

Answer

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 >@.

Comments