Swift should provide native regular expression literals
| Originator: | hoop33 | ||
| Number: | rdar://17306132 | Date Originated: | 6/13/2014 |
| Status: | Open | Resolved: | |
| Product: | Developer Tools | Product Version: | |
| Classification: | Feature (New) | Reproducible: | Not Applicable |
Summary:
This is a duplicate of rdar://17257306
Any modern language should natively support regular expression literals without resorting to constructing a class and interpolating a pattern into a string. Of course a class equivalent would be driving the functionality and be helpful for more dynamic construction of patterns. Regex literals can really clean up code and make it more readable.
There is not a single mention of Regular Expressions in the Swift book and while I know we still have NSRegularExpression, it is cumbersome to use.
Proposal:
A regular expression literal might look like the following:
let pattern = /[Cc]ats?/
A simple way of detecting a match:
if pattern.isMatch(text) {
…
}
It would be great if this could be simplified to a special operator, such as =~ in Ruby.
Also enumerate over matches:
for match in pattern.matches(text) {
println(“Found \(match.value) at character position: \(match.position)”)
}
Support for named groups:
let naiveEmailPattern = /(<?username>[A-Za-z-_0-9])@(<?company>[A-Za-z0-9_-]).corp/
for match in naiveEmailPattern.matches(text) {
let username = match[“username”]
let company = match[“company”]
let email = match.value
println(“The user \(username) works at \(company) and has an email address of \(email)”)
}
Version:
5.0.2 (5A3005), 10.9 (13A598)
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!
rubyesque matcher
if "Cats" =~ /[Cc]ats/ { ... } // -> 0 // returns Int? position of first match