問題
Swiftで正規表現を書くと
let regex = "\\A\\s*[-+*]\\s*\\S+\\z" // Markdownの箇条書きか判定する雑な正規表現
と書かないといけない。これでは不便ですね。
解決方法
Swift 5からRaw strings literalの仕組みが導入されました。このliteralを利用すると
let regex = #"\A\s*[-+*]\s*\S+\z"# // Markdownの箇条書きか判定する雑な正規表現
と書けます。 #"ここに文字が入る"#
という記法です。これで、わかりやすく正規表現を記述することができますね。
余談
また、このliteral内では "
も利用することが可能で
let string = #"The word "bookstore" is a compound consisted of "book" and "store.""# // => The word "bookstore" is a compound consisted of "book" and "store."
この様に文字列内で "
をそのまま利用できます。また、文字列内で "#
を使いたい場合は
let string = ##"The word "bookstore"#hashtag"## // => The word "bookstore"#hashtag
この様に、前後の #
を増やしてあげれば良いです。
さらに、文字列補間もしたいですよね。そういう場合は
let name = "太郎" let string = #"犬の名前は "\#(name)" です。"# // => 犬の名前は "太郎" です。
と \#(name)
とすることで利用できます。