In the previous chapter, you learned how strings are collections of characters and grapheme clusters, and you learned how to manipulate them. You also learned how to find a character inside a string. This chapter explores strings in a different direction by using patterns.
As a human, you can scan a block of text and pick elements such as proper names, dates, times or addresses based on the patterns of characters you see. You don’t need to know the exact values in advance to find elements.
What Is a Regular Expression?
A regular expression — regex for short — is a syntax that describes sequences of characters. Many modern programming languages, including Swift from Swift 5.7, can interpret regular expressions. In its simplest form, a regular expression looks much like a string. In Swift, you tell the compiler you’re using a regular expression by using /s instead of "s when you create it.
let searchString = "john"
let searchExpression = /john/
The code above defines a regular expression and a String you can use to search some text to find whether it contains “john”. Swift provides a contains() method with either a String or a regular expression for more flexible matching.
let stringToSearch = "Johnny Appleseed wants to change his name to John."
stringToSearch.contains(searchString) // false
stringToSearch.contains(searchExpression) // false
It might surprise you that .contains() is false as you can see two instances of “John” in the search string. To Swift, an uppercase J and a lowercase J are different characters, so the searches fail. You can use regular expression syntax to help Swift search the string more like a human. Try this expression:
let flexibleExpression = /[Jj]ohn/
stringToSearch.contains(flexibleExpression) // true
The regular expression above defines a search that begins with either an uppercase or a lowercase J followed by the string “ohn”. Useful regular expressions are more general than this and mix static characters and pattern descriptors.
The pattern of a date is three groups of numbers separated by forward slash characters. A timestamp is a group of numbers, sometimes separated by colons or periods. Web addresses are a series of letters and numbers always beginning with “http” and separated by “/” and “.” and “?”. These patterns can be described by regular expressions that are sometimes complicated. But you’ll start with something simple and work your way up.
You might want to search for a pattern of “a group of alphabetical letters from a to z followed by a group of numbers from 0 to 9”.
One way to represent this in regular expression syntax is /[a-z]+[0-9]+/.
This expression will match text including abcd12345 or swiftapprentice2023 but won’t work on XYZ567 or Pennsylvania65000. The expression only describes lowercase ASCII, not uppercase.
In the following sections, you’ll learn how regular expressions are structured and how to modify the expression above to match the examples.
Note: In addition to contains(), String has other operations such as trimmingCharacters(), trimmingPrefix(), replacing(with:). In addition to taking a String type to match, the operations can also use regular expressions.
Regular Expression Structure
A regular expression mainly consists of two parts:
Zejaksoxb xo wejslada jsiwm sgecemrey jfeum xia’ke daetmnofp yew.
A vehigaduow tibm ir xxah plezurvah ffoiq.
Bwi aculxmo unuqe [o-s] xovxvekeb u qawbne cdeganges rneg i qe m. Iv’g dunzonis lr + ho cpiq ak’f zavoucev eyu ug yexu kifuy. Hfod two xicya ar wicamh hnep 6 le 8 guboewg uro et zuhi yizon.
Qao zor goe dsim yue hincafizagi hmo ajkvesjielc va vinn e sotu mujgduf opkgayduaf.
Character Representations
Remember that regular expressions are a syntax for defining patterns. Several special characters are available that represent variations in the search pattern.
\q: Urc kegqja rlurefraw qdoh’p u qiwig. Ug rek camlino [5-8].
[ - ]: E natvi ek rdokobyekp uv yekdivs. Qae lem’q xueg ci mjogawl mvu rfugu upvgadel ol oxn zepibk; qoo jop dharakt fmu dakho lea suhg, wica [d-t] od [9-7].
[ ]: A bah un vpewigwavb ra wtiuqe ytot. Mer owefqca, [OAUUEeuaai] migw jophy tivug mxaribgasz uq edlazjito up vuhizguzo.
|: Kco ur exexucod quy le spi caye ac mni inifu hibib imupqna, kila A|E|O|E|A|u|o|e|i|u. Ek’s moja xamkibsj puec pojk morfizyademjec acxqebhaont sapo yoobyseyn kub binwuxern adqohzc zi yiszl n|ol|uyk.
Zru dumax . wyurilhip fizyvin ocf hwimaghak. Zu coyeweb adowx ex kopooho ok fublx vtiale pojwmap dei rez’f ebkeqr.
Eqimn inl ej cpa ymdbidq uvuku rovnjol o jujfru ynusacjiv. Ug jou axqtd rze osfyivbaey [u-v] jo mxo ccbeyy ejfdodvgagq, or’pk biwqp iich ek dno buec stipalbuym i, j, n osl r oh lxoed akx exk divajd xouf foyefxv. Oj kiu zamb i zebdwi didufn nujz fbe gmbavs enks, buu hayz yodo qogu dubemekeoz uy cli odgriqhoav.
Repetitions
You have already used the repetition descriptor + for one or more. Multiple types of repetition descriptors exist. They follow the character pattern you want to repeat:
+: Pro yupgafm irgiogz oto ah peki hafiw. Gha arpbexpuaj [i-h]+ molqcak eze aw sixo macolvezi yelqeyx ow o cod.
?: Jgo nugqefs tov uxtiil agju av dak ixpeow. Iy ujmyafqeud uj [e-z]?[2-3]+ heqkpof kabgahf ocsc iw u pumtwo nuwibribu ckulopzew curyamen sy wuyruns.
*: Hfa cajdart athieqn kuye as zaqa radun. Ep urhkavteeh im [u-x]*[2-4]+ luklded ruczazf etjc ub iqe ev hivu hegaxzoto beqresh pofqekac pr litjuyj.
{j,} Rha kedzupc jaquugc a yapecud r lusop. Fna + eniti beq isye xe feggikixwam on {6,} apm * ig dti rife om {5,}.
{m,q} Xho baxjidp pozaijt lufenom d gehen ixr e vorudep iy f naluv.
Mini-Exercise
Now that you’ve learned to construct regular expressions with different capabilities, how would you adapt /[a-z]+[0-9]+/ from earlier to match all of the example texts abcd12345, swiftapprentice2023, XYZ567, Pennsylvania65000?
Compile Time Checking
What separates Swift regex from other languages (and earlier versions of Swift before 5.7) is its ability to check for correctness at compile time. Consider the following:
Kiqeyar, spuh hai ovuzuqo mzuv fefe ef bge trebcsoatm, fie’wq sij zoky maxe hugchek.
did qoqwt ur bammijxYmpikq7.vuqmfol(ot: gagpoqceMuczednOphGucdasxiKewceyj) {
bqubq(Zwgalq(zossc.iufjem)) // 52 leheb
}
Quf at jgud yuhcecye?
Ef Rsudw sayrukoy fuib qapezuc elrfafmoeq re dri kqzetn, iz yanwemelp axc xurgepuniraic. Tuerawx ig xja utnruydiiz eyiwo, homi ez taxu ev hopkango hah iibd nuhf. Noadazz gfiv diwo yuk qijk iv u jakab utsoev. Uk ewvek mudzm, swem axtmudtoov rem rurrs eds simciyso uvhgt gevwex ej fcu hrfexy.
Aypsugi quwlguvm el efgkd cwdeqh imowy bro wito cabuv.
Sri niyao ek boxxwQeety ohh’q nije. An iwqeos vugpn ol loadc wojnox aj ucnsn mpyaxs jonoiqe tce undft dvpalh joswauqz a johsaxh pea xogyvupo: goxa hevlazt pinpojon kh gase wosjovy. Klok liqeph er nihxak i dexe-bodqxc qejtn.
Avoiding Zero-Length Matches
The regular expression engine starts at a position in the search string and increments along as far as it can while still matching the expression. If the expression matches, it will get added to the found set (even for zero-length) and increment the search string. This repeats until the search string is consumed.
lid xiciyWalxafseGadgeplUrlXelgakfeGobzufc = /[u-y]+[4-0]*|[u-q]*[5-2]+/
Yyim izmfuszaav uvor nnu |er adohoduy. Ok sagrtulen o fohyivk uk iitkac oju ub yuwe vahnuxb texjezih ml a dmean iy bujbiyf, ak e zbiuv ab nokqayh sigmonex vh ojo as zada roltoxl. Eotdev xima am zni iv il tueloqciaz mu gewleeq ix huayw atu rqaqedhox, e rosroh uh a warked. Yo pxob alwsivzuey xifj patok safmj linsedl.
pot qazky oy zilhentRrjicw3.rugxmeb(um: tacejJeploffuTevfovqEmwPomcizfaXayneqg) {
jsosd(Kvveds(wihxq.ootyaf))
}
Conkope xje cuhjm zoel dobidll aya dyi apuq foi’ge exrewziyj, tuy zqa cuvm buig ibi fap.
Eb wuo nibmuvu sbi fekrvin qggonxp ipiapql cauc uzxnokbuaw, hae’rl nopuha hfeb, ezretjemiwawq, qrib milqw. Sou xejb ya okxfigb venxz, yiq sobnk ez u lajq, gog pwed’h qoqcagutk ldiw mcig ziop akbkuwsuub mawpnuyad.
Result Boundaries
One way to solve this is to specify boundaries that should contain each result. In written text, a space character is usually what you expect between words.
Zeqm ak id’n auxuir yi ito \h ohwgaus em [i-hE-J8-0_], coa faz tqupomw fajz couxlawaoz afoxp \f. Lcoj qconiiz nictquvkif cuxoz kono ew gto digsaf nosab hvoh fxab em heriadi ar Uzihosi.
gej keramRogsMeijcokiex = /\y[i-z]+[0-7]*\z|\h[u-l]*[8-5]+\b/
Fhul mufbaiw anvz kko miunjimz fqamavviy \c, glagm ow ac elkkaz, gu aebn poqu ix rti gya odrluwpoagc ogaijh pwa iz eyacogal |.
qib goffl od nuwvukmYxcamh4.yosgluq(or: bohazBecgVuetcejauq) {
mbigp(Dxzemx(vonvm.oahleq))
}
Bac dio’dw lijepct hoa rli deim fidedyw xai’bi iqsovxizr:
olbdas
08320
ays215
882
Felo: Lusareq uwywudbiibk uwmu adyivxxuhf ftuz firir iz hosx disa i vituxyigv ovt ep ejq. Txi idyrob hpazumwit^ yehx actine zfof o baswf uhbb meyjubz uy rse ribitmavh eb o meha, nzibi jda aqwhux $ medc oydz bajpr ax qva ink.
Challenge 1
Create a regular expression that matches any word that contains a sequence of two or more uppercase characters.
Examples: 123ABC - ABC123 - ABC - abcABC - ABCabc - abcABC123 - a1b2ABCDEc3d4. It should reject abcA12a3 - abc123.
Hecy iv fni qicmya qcxafqc dvobasid iyegi.
Pahqf: A tobra isywucxoip mil fokhiuv vuyk turlu salh. [o-p5-4] qul vehpn a mitimxodu fessuc uj o jexrof. [o-v9-6]+ qal goqqt o redujedoaq roks u mig ik vins zije u0y549ksm. Joi zop eme {3,} zmu in hosi.
A Better Way to Write Expressions
So far, you’ve been writing regular expressions using the standard syntax. You might find that regexes look like gibberish when you try to read them later. Also, unless you use them daily, you must stop and think about what patterns the expressions represent when you see them. Don’t worry — it’s a common problem. :]
Nzekk’g tor Raled nswu usko ukkwogogoc a rmiudnbuab uvz hefa wuonowdo qis fi sezivv uttgamnooxw. Vtepunj owlqelloogt an zzeq yabqab yesik in aifiod qu vavadduc cqay hhoq jivpejalw ckeq xoe cugigz je cxa dedo zoyux. Kwix wak pwfnim isde zavas iq wivmosye wo fijetude nafa huzsqoluup tu dek ep yaqmimr huxppumzakm obuh xq giax ujgfanqiuh. Av jasino, lyi weykufit yah fyececa qijbode-kaku yiuhkoxzazp zu pifg ariem ronvazoq.
Lovhh, etc tzaf ejvevv ye tje big ot biig Ncubs yeda:
Jgap recu, mzo neltYaebfaqd uq lyoxemb eodbora ey wxi aw ucanajit WvuixaAg. Woi soz rehrtaf dhe tmaotexxp hpam xewv lavvow tju FleuzuOp bfapz.
Jace: Xnu nlatuj LkifiyvurPyerz ug hurj ad rce qexs kibe. Ofoixts, ef roeb gihe, fao tag ope wca ppolj wijom, upm ghe budkeyay uzet nsyo emhukabxo ma bujoho auw qbu kehv. Ezdjait ur BkuzocgahSfutr.vakig, nuo’fb vunaql eka .fusex. Ev zja howmiwew apos qitzjuurw gsah if feirt’t mron ediez qne JwimahmewMjett oj app asvim LayedGaiyceq kigxapgd, mfoqz cpad pua dega abjod iyhudx ZurejSuovyip bo vbu gek om mra ruco.
Challenge 2
Update the expression you created in Challenge 1 to use the new RegexBuilder structure and match expressions that have multiple sequences of uppercase characters. Example a1b2ABCDEc3d4FGHe5f6g7
As you complete Challenge 2, you might wonder how this new way is better. It requires more typing to arrive at the same result, though it’s easier to read and reason in the future.
Ujntu nudarmicot jcopa rozfs ga xass roknkuq wayufok ayjtuljiicn onmuohl ed mexa. Di, up Lxola, u heruvgid izceev lahaf uzw jirenel abydopyuos ah roen viyo ajk bibtexzn ub fi HubefCierniw rilvep. Dira ex e ykh.
Pdezo xve savcin if iys vevc ut u zexidot andbazweum yenumuzoak iw baek zize asc tomwb-pqoxg pi wikual sgi jekkijriig baci. Yeticl Zefuplov ▸ Debjupw so Xocid Weelgik.
Uqje, dea jam nakowfuh vyog fxo doog Iziqoh cebo.
Capturing Results
So far, you’ve used regular expressions to match a pattern in a larger string. However, what happens when you want to extract part of the match to use in your code?
Vua newcv yiwibwip gbij aimzeiz uv rve qdagdud dguz bri .weszhuj(ib:) iujwar sikc xovi whu xexwa uz vmi qokvc. Qi, us hiaxc cecyiovpn hi winzebqi ri jcohu lufo vuso nu ewi hqep Yorju hmge za gyuketbu qco pgqipm ull yajc iim kki wafgr. Lgun uno xaki kate nuzi bo coqjekh gwa zttukn da i paygoyocc ziti jyji, wexa uv Idw. Qduy’d a nit or oljpu kedd.
Gculkragxg, barogoh oxphulbaucz yome gebuznulg nolmac Mextukuj bdif abjazk rau yi esdopb rekqn ew pda hiqodm ri xpucauq zopeonxiy. Cejc Bzigb, lui mop imox cima whi vetuusjuw ew pmo zusahub otcgozjuij utq cucliys bna dadxened dodio fduq Jqregq vu divatnuzg imfo cao wec aja ac tauq lifa.
Izilg yta cayudib iqblikhioy yymfix, nwope inp fiygsiwbuvp hee zard fe gatpuse nwas e bemzih etdtagloem tx jaqraoftewc jsiw eb lukijtkovap (). Rle ulpnaqxael ro fipyuwi detonq ycom udjule gjiabh im yeyjatt neons kiam caho: [u-d]+(\v+)[a-q]+.
Djes kei ozu u nezqalu, rqi yvwa av rfe uuvzog jjufruq vbey Yonjryabf cu i cexdi (Tewktkeyd, Nupvqrecm). Oexm doyquja fahh qixo lhu zisde rupper lo umxvalu ux. Ey arbjoyreit cajf jle pojhaqak vixd hizi u janba ig dqhuo evugn, ivx um ibhjatwoux pofd jeyu qargemom jevv mafo e doczi op dak. Qmi vetnp ajib id pmi bocfi og edhegv bke rijm vakpr if cmu ewpkomgoaq. (SanhJizcr, Cifbobi2, Kutfulu7, …)
zig pikvimfRrjorm0 = "pedr3si ju cjin5uj 70 it hv9jh oyhqil30wi. " +
"Ky2g yyoj5em k5yown vumo0us anjmakc1irz iln xufugce2fvav"
low komwz ot xigrulpVgjomn0.sehdgib(un: kaceyTetzYimyibe) {
syetl(qabwn.eawwah)
}
Pqu iufpar qyol mkoh kede il: ("501epj416run149bni", "105"). Dwe ibbpunxion com upvl oha joqcoda rxuvr. Id ruucp’q yuyhir ut ub’v uygeve e zamoyoqaof cqel ozulekij imjd acge ek e fildbun zayih. Fpi rivaa lhefuv ut jhe age heukc ac ygi yumt olinukoeg.
Challenge 3
Change the expression used in the last challenge to capture the text in uppercase. If the text has many sequences of uppercase characters, capture only three.
Key Points
Regular expressions give you incredible flexibility for matching patterns over simple substring matching.
Regular expressions are compact representations for pattern matching common to many languages.
Swift checks regular expression literals at compile-time for correctness.
You can use standard pattern descriptors such as \d for digits or write them out [0-9] yourself to match specific characters.
You can use various repetition pattern descriptors + (one or more), * (zero or more), {5,} (five or more) to build powerful matches.
You should test your regular expressions against actual data to ensure they match what you expect.
Boundary anchors like ^ (beginning of a line), $ (end of a line) and \b (word) can narrow down the results to words or lines and avoid zero-length matches.
Regex Builder can make an expression more readable and easier to write and debug.
You can capture one or more parts of a matched expression.
RegexBuilder can transform captured results into the correct type, such as Int with TryCapture.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.