1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftのStringの中のバックスラッシュをreplacingOccurrencesで置換しようとする勘違い

Posted at

おそらくこちらのstackoverflowと近しい課題にぶち当たったのだが、よくよく考えるとなんとも馬鹿な勘違いをしていたのでメモ。

単純に言うと以下の文字列からバックスラッシュ\を削除しようとしていた。

var str = "Hello, \"playground"
print(str) // => Hello, "playground

str.replacingOccurrences(of: "\\", with: "")
print(str) // => Hello, "playground

お分かりいただけるだろうか?

本来Stringというのは"などの特殊文字をエスケープするためにバックスラッシュをつける。だから上記のstrは出力された際にバックスラッシュはつかない。が、今回対象の文字列がhtmlであり、かつ以下のようにXcodeのデバッグエリアに白黒で出力されていたので「バックスラッシュがHTMLの中に入ったまま出力されているから画面の表示が崩れたのだ」と錯覚してしまった...orz

スクリーンショット 2020-04-07 18.33.51.png

var str = "<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n <head> \r\n "
str.replacingOccurrences(of "\r\n", with: "")
print(str) // => "<html xmlns=\"http://www.w3.org/1999/xhtml\"> <head>   "

str.replacingOccurrences(of "\\", with: "")
print(str) // => "<html xmlns=\"http://www.w3.org/1999/xhtml\"> <head>   " あれ?変わってないな‥

str.replacingOccurrences(of "\"", with: "")
print(str) // => "<html xmlns=http://www.w3.org/1999/xhtml> <head>   " ダブルクオーテーションも一緒に消すと消えるなぁ(シンタックスハイライトありならダブルクオーテーションを削除してるだけなのだが気付けない)

base64からの変換であったためか、改行コードの/r/n/tなどが入っていたために勘違いを誘発しやすかったようだ。本来のStringの記法がふっとんでいた。Unicode文字の\x5cで置換しようとしてみたりで完全に迷路になった。

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?