[swift-evolution] Empower String type with regular expression

David Waite david at alkaline-solutions.com
Tue Dec 8 14:40:26 CST 2015

It sounds like you are asking for two things:

=~ operator support for regular expressions
regular expression literals

I would love to see regular expressions be more usable in swift, but my opinion is that =~ is a bad idea, and regex literals have tradeoffs important to consider.

For =~ :
1. The semantics of the =~ operator in other languages maps to a return value of Int? - matching position or nil with no match. This means you would likely need to write if str =~ foo != nil { … }
2. The above is considerably longer and harder to read than (say) if foo.matches(str) {
2. The semantics of the =~ operator produce state around matched groups, which is usually exposed to the language as either thread-local or block-local data.
3. The =~ operator only makes sense when applied to strings (or some other random access text source) and regex

For regex literals, my only concern is that it makes regex a language feature over an extended or standard library feature. If there is ever a desire to have Swift usable on embedded systems, you would likely want to be able to drop regular expression support.

On the flip side, regex may require code generation/compilation to work. A statement like:

while Regex(“foo”).matches(currentLine) { ... }

has a performance hit in generating the regex parser on each invocation of the loop.

Not only does having a literal syntax allow the compiler to optimize this to generation of a single processor, but the compiler could even generate IL to do said processing.

> On Dec 8, 2015, at 1:14 PM, Jerome Paschoud via swift-evolution <swift-evolution at swift.org> wrote:
> I would like to see the String type to support regular expression per default. I think that a language that advertise itself as being a good scripting language should provide in its default implementation an easy way (=~ for example in Perl) to use regular expressions. I know that one can use the NSRegularExpression, but who really what to first create an NSRegularExpression object(whit all the nice escaping operation that come with every \), then get a NSTextCheckingResult, then get a range (and what I mean is a NSRange and not a NSRange<String.Index>) and finally perform slicing of your original string. 
> I realize that it could be considered as purely syntactic sugar, but what a nice one.
> Jérôme
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

More information about the swift-evolution mailing list