Search code examples
swiftstringmultilinestring-literals

What kind of newline character is in my multiline string literal?


I'm trying to replace a new line with something, or remove it, but I can't even figure out what kind of new line character it is. I've tried \n and \r as a regular expression:

var testStr =
"""
    .db $82, $14, $2c, $62, $26, $10, $28, $80, $04
    .db $82, $14, $2c, $62, $26, $10, $28, $80, $04
    .db $82, $08, $1e, $5e, $18, $60, $1a, $80, $04
    .db $82, $08, $1e, $5e, $18, $60, $1a, $86, $04
    .db $83, $1a, $18, $16, $84, $14, $1a, $18, $0e, $0c
    .db $16, $83, $14, $20, $1e, $1c, $28, $26, $87
    .db $24, $1a, $12, $10, $62, $0e, $80, $04, $04
    .db $00
"""

testStr = testStr.replacingOccurrences(of: "^\\r*", with: "!", options: .regularExpression)
testStr = testStr.replacingOccurrences(of: "^\\n*", with: "!", options: .regularExpression)

print(testStr) // does not replace new lines

Solution

  • Looks like you've made the RegEx a little more complicated than it needs to be. As mentioned in the comments, you can remove the beginning anchor ^ and the *. The newline characters the multiline literals creates are caught by \n

    Also, remember that your indentation matters with multiline string literals. You want the ending """ to be at the level at which the text is indented.

    var testStr =
    """
    .db $82, $14, $2c, $62, $26, $10, $28, $80, $04
    .db $82, $14, $2c, $62, $26, $10, $28, $80, $04
    .db $82, $08, $1e, $5e, $18, $60, $1a, $80, $04
    .db $82, $08, $1e, $5e, $18, $60, $1a, $86, $04
    .db $83, $1a, $18, $16, $84, $14, $1a, $18, $0e, $0c
    .db $16, $83, $14, $20, $1e, $1c, $28, $26, $87
    .db $24, $1a, $12, $10, $62, $0e, $80, $04, $04
    .db $00
    """
    
    testStr = testStr.replacingOccurrences(of: "\\n", with: "!", options: .regularExpression)
    
    print(testStr)
    

    Yields:

    .db $82, $14, $2c, $62, $26, $10, $28, $80, $04!.db $82, $14, $2c, $62, $26, $10, $28, $80, $04!.db $82, $08, $1e, $5e, $18, $60, $1a, $80, $04!.db $82, $08, $1e, $5e, $18, $60, $1a, $86, $04!.db $83, $1a, $18, $16, $84, $14, $1a, $18, $0e, $0c!.db $16, $83, $14, $20, $1e, $1c, $28, $26, $87!.db $24, $1a, $12, $10, $62, $0e, $80, $04, $04!.db $00