Fix String.unescaped

This commit is contained in:
1024jp 2023-11-30 20:40:48 +09:00
parent db22c49acd
commit 00ecfed2ec
3 changed files with 21 additions and 12 deletions

View File

@ -16,6 +16,7 @@ Change Log
### Fixes
- Fixed an issue that the “unescape replacement string” option could not unescape consecutive backslashes correctly.
- [beta] Fix an issue that some active actions were not listed in the Quick Action bar.

View File

@ -39,18 +39,19 @@ extension String {
/// Unescaped version of the string by unescaping the characters with backslashes.
var unescaped: String {
// -> According to the Swift documentation, these are the all combinations with backslash except for \\ itself.
// -> According to the Swift documentation, these are the all combinations with backslash.
// cf. https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID295
let entities = [
"\0": "0", // null character
"\t": "t", // horizontal tab
"\n": "n", // line feed
"\r": "r", // carriage return
"\"": "\"", // double quotation mark
"\'": "'", // single quotation mark
#"0"#: "\0", // null character
#"t"#: "\t", // horizontal tab
#"n"#: "\n", // line feed
#"r"#: "\r", // carriage return
#"""#: "\"", // double quotation mark
#"'"#: "\'", // single quotation mark
#"\"#: "\\", // backslash
]
return entities.reduce(self) { $0.replacingOccurrences(of: #"(?<!\\)((?:\\\\)*)\\"# + $1.value, with: "$1" + $1.key, options: .regularExpression) }
return self.replacing(/\\([0tnr"'\\])/) { entities[String($0.1)]! }
}

View File

@ -66,10 +66,17 @@ final class StringExtensionsTests: XCTestCase {
func testUnescaping() {
XCTAssertEqual("foo\\\\\\nbar".unescaped, "foo\\\\\nbar")
XCTAssertEqual("\\foo\\\\\\0bar\\".unescaped, "\\foo\\\\\u{0}bar\\")
XCTAssertEqual("\\\\\\\\foo".unescaped, "\\\\\\\\foo")
XCTAssertEqual(#"foo\n\n1"#.unescaped, "foo\n\n1")
XCTAssertEqual(#"\\"#.unescaped, "\\")
XCTAssertEqual(#"\'"#.unescaped, "\'")
XCTAssertEqual(#"\""#.unescaped, "\"")
XCTAssertEqual(#"a\n "#.unescaped, "a\n ")
XCTAssertEqual(#"a\\n "#.unescaped, "a\\n ")
XCTAssertEqual(#"a\\\n "#.unescaped, "a\\\n ")
XCTAssertEqual(#"a\\\\n"#.unescaped, "a\\\\n")
XCTAssertEqual(#"\\\\\t"#.unescaped, "\\\\\t")
XCTAssertEqual(#"\\foo\\\\\0bar\\"#.unescaped, "\\foo\\\\\u{0}bar\\")
XCTAssertEqual(#"\\\\\\\\foo"#.unescaped, "\\\\\\\\foo")
XCTAssertEqual(#"foo: \r\n1"#.unescaped, "foo: \r\n1")
}