قالب وردپرس درنا توس
Home / IOS Development / Regular expressions in Swift – NSHipster

Regular expressions in Swift – NSHipster



Like everyone else in the Pacific Northwest,
we have snowed into the weekend.
To pass the time,
we decided to break out our stash of board games:
Carcassonne, Machi Koro, Power Grid, Pandemic;
We had many good choices available.
But cooped up in our home for the afternoon,
we decided on a classic:
Cluedo .

Me, I'm an avid fan of Cluedo –
and yes that's what I should call it.
Because they were born and raised in the United States,
where the game is sold and marketed exclusively under the name "Clue",
I insist on referring to it by their proper name.
(Otherwise, how would we refer to the 1985 movie adaptation?)

Ak,
my relentless pedantry often leads me to miss invitations to play.
If anyone were to ask:

  was    invitation    =    "Hey, would you like to play Clue?" 
  invitation .   contains   ( ] "Cluedo" )    // false 

… I had no idea what they were talking about.
If only they had bothered to express it correctly,
there will be no doubt about their intention:

  invitation    =    "Fancy a game Cluedo ™?" 
  invitation .   contains   (  Cluedo ")    // true 

Of course,
a regular expression
would allow me to relax my demanding standards.
I could listen for / Clue (do)? ™ /
and never miss another invitation.

But who can be bothered to find out regexes in Swift, anyway?

Well,
sharpen your pencils,
collect your detective notes,
and heat your 6-sided cube,
because this week at NSHipster,
We crush the case to the heavy class known as NSRegular Expression .


Who killed common expressions in Swift?
I have a suggestion:

It was NSRegular Expression in the API, with the heavy usability.

In another language,

  • Do you need to extract a value from a templated string? ] : regular expression

But in Swift,

  • do you need to analyze XML?
    Tree :
    You have to go through problems with
    initialization of a NSRegular Expression object
    and converts back and forth from String varies to NSRange values.
    It's a total drag.

    Here are the good news:

    1. You don't need NSRegular Expression to use common expressions in Swift.
    2. Last additions in Swift 4 and 5 make it much, much nicer
      to use NSRegular Expression when needed.

    Let's question each of these points, in order:


    raw string literals
    introduced in Swift 5
    is a perfect fit to declare common expression patterns,
    which often contains setbacks (as for b metacharacter)
    otherwise it had to be escaped.

    It solves our problem of missing invitations.
    The next question is how you respond in shape.