Suppose you know PCRE, specifically NSRegularExpression
.
How to convert to Swift's Regex DSL?
First, you don't have to. With JavaScript modern /literals/
, you can keep typing line noise. But if you're itchy to try the shiny, this table can get you going.
Tip: When exploring, look for types conforming to RegexComponent
(scroll to the bottom).
� represents 'some regex', 'whatever', and 'etc.'
I want to match | NSRegularExpression |
Swift Regex |
---|---|---|
Anchors | ||
Word Boundary | \b |
Anchor.wordBoundary
|
Start of Line | ^ |
Anchor.startOfLine
|
End of Line | $ |
Anchor.endOfLine
|
Characters | ||
Any Character | . |
CharacterClass.any
|
Newline | \n |
CharacterClass.newlineSequence
|
Digit | \d |
CharacterClass.digit
|
Word Character | \w |
CharacterClass.word
|
Whitespace | \s |
CharacterClass.whitespace
|
Character set | [Helo] |
CharacterClass.anyOf
|
Lookaround | ||
Positive Lookbehind | (?<=Hello)World |
Not Available |
Negative Lookbehind | (?<!Hello)World |
Not Available |
Positive Lookahead | Hello(?=World) |
Lookahead { � }
|
Negative Lookahead | Hello(?!World) |
NegativeLookahead { � }
|
Misc | ||
Capture Group | (World) |
Capture { � }
|
Non Capturing Group | (?:World) |
Implicitly in trailing { � } |
Explicitly with Regex |
||
Backreference | \1 |
Reference
|
Or | �|� |
ChoiceOf { � }
|
Quantifiers | ||
Optional | �? |
Optionally { � }
|
╠ Lazy | �?? |
Optionally(.reluctant) { � }
|
╚ Possessive | �?+ |
Optionally(.possessive) { � }
|
Zero or More | �* |
ZeroOrMore { � }
|
╠ Lazy | �*? |
ZeroOrMore(.reluctant) { � }
|
╚ Possessive | �*+ |
ZeroOrMore(.possessive) { � }
|
Once or More | �+ |
OneOrMore { � }
|
╠ Lazy | �+? |
OneOrMore(.reluctant) { � }
|
╚ Possessive | �++ |
OneOrMore(.possessive) { � }
|
Exactly n times | �{n} |
Repeat(count: n) { � }
|
At least n times | �{n,} |
Repeat(n...) { � }
|
At most m times | �{0,m} |
Repeat(...m) { � }
|
n to m times, inclusive | �{n,m} |
Repeat(n...m) { � }
|