swiftregexshebang

Can regex literals be used in a Swift script?


I would like to make a Swift script with “shebang” notation that uses a regex literal. For example:

#!/usr/bin/env swift

let message = "Hello, world"
print(message.replacing(/[aeiou]/, with: "[vowel]"))

In the question Does the Swift Package Manager support regex literals?, I learned how to make this code work in the Swift Package Manager.

Could it be made to work as a Swift script, or do I have to wait for future updates?


Solution

  • As said in the linked post, regex literals is an opt-in feature for now, and you need to use the -enable-bare-slash-regex option.

    Just change the shebang to:

    #!/usr/bin/env swift -enable-bare-slash-regex