【问题标题】:What kind of newline character is in my multiline string literal?我的多行字符串文字中有什么样的换行符?
【发布时间】:2022-01-03 23:00:29
【问题描述】:

我正在尝试用某些东西替换新行或删除它,但我什至无法弄清楚它是什么类型的新行字符。我已经尝试将 \n 和 \r 作为正则表达式:

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

【问题讨论】:

  • 在我看来,您使用的是开始锚点“^”,后跟只匹配行首的字符。您是否尝试过从正则表达式中删除“^”?
  • 看起来像CRLF
  • @MYousefi,删除“^”匹配每个字符。
  • @aheze 我可以将 CRLF 与“^\\r\\n*”匹配吗?它似乎没有抓住它。

标签: swift string multiline string-literals


【解决方案1】:

看起来您使 RegEx 变得比需要的复杂一些。如 cmets 中所述,您可以删除开始锚点 ^*。多行文字创建的换行符被\n捕获

另外,请记住,您的缩进对于多行字符串文字很重要。您希望结尾 """ 处于文本缩进的级别。

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)

产量:

.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

【讨论】:

    猜你喜欢
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2018-03-04
    • 2014-04-29
    • 2017-06-13
    相关资源
    最近更新 更多