Fix unescaping

This commit is contained in:
1024jp 2017-12-09 13:28:14 +09:00
parent 440a2ccddb
commit 96becf6b5f
3 changed files with 17 additions and 13 deletions

View File

@ -6,6 +6,8 @@ Change Log
--------------------------
### Fixes
- Fix an issue where backslaches in replacement strings were not unescaped correctly.
- Fix an issue where items in the Script menu were not sorted by prefix numbers.
- Fix a possible crash on handling documents with an invalid shebang.
- Fix Japanese localization.

View File

@ -41,20 +41,22 @@ extension String {
// -> According to the following sentence in the Swift 3 documentation, these are the all combinations with backslash.
// > The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quote) and \' (single quote)
let entities = ["\0": "\\0",
"\t": "\\t",
"\n": "\\n",
"\r": "\\r",
"\"": "\\\"",
"\'": "\\'",
let entities = ["\0": "0",
"\t": "t",
"\n": "n",
"\r": "r",
"\"": "\"",
"\'": "'",
]
return entities
.mapValues { try! NSRegularExpression(pattern: "(?<!\\\\)(?:\\\\\\\\)*(\\\\" + $0 + ")") }
.reduce(self) { (string, entity) in
string.replacingOccurrences(of: entity.value, with: entity.key)
entity.value.matches(in: string, range: string.nsRange)
.map { $0.rangeAt(1) }
.reversed()
.reduce(string) { ($0 as NSString).replacingCharacters(in: $1, with: entity.key) }
}
.replacingOccurrences(of: "\\\\(?!\\\\)", with: "", options: .regularExpression) // remove all single backslash
.replacingOccurrences(of: "\\\\", with: "\\")
}

View File

@ -10,7 +10,7 @@
------------------------------------------------------------------------------
© 2015-2016 1024jp
© 2015-2017 1024jp
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -43,9 +43,9 @@ 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\\\\\\nbar".unescaped, "foo\\\\\nbar")
XCTAssertEqual("\\foo\\\\\\0bar\\".unescaped, "\\foo\\\\\u{0}bar\\")
XCTAssertEqual("\\\\\\\\foo".unescaped, "\\\\\\\\foo")
}