代码之家  ›  专栏  ›  技术社区  ›  lf_araujo

使用Swift从yaml块中删除行

  •  0
  • lf_araujo  · 技术社区  · 7 年前

    我的目标是从字符串变量中删除Yaml键和值,但我失败了。

    MWE

    let testMe = """
    --- 
    # Metadata
    title: hum
    author: jecatatu
    email: jecatatu@gmail.com
    ---
    This is more text outside the yaml block
    """
    

    目标是有一个字符串:

    let testMe = """
    --- 
    # Metadata
    title: hum
    ---
    This is more text outside the yaml block
    """
    

    到目前为止,我的代码看起来像:

    var email = "jecatatu@gmail.com"
    let emailline = "email: " + email
    let document:String = testMe.replacingOccurrences(of: emailline,  with: "")
    

    问题

    • 上述操作不起作用,也就是说没有从yaml块中删除电子邮件行,我如何删除包含作者和电子邮件信息的整行内容?
    1 回复  |  直到 7 年前
        1
  •  1
  •   Smartcat    7 年前

    如果您在Swift 4运动场中放置以下物品:

    import UIKit
    
    var testMe = """
    ---
    # Metadata
    title: hum
    author: jecatatu
    email: jecatatu@gmail.com
    ---
    This is more text outside the yaml block
    """
    
    var email = "jecatatu@gmail.com"
    let emailline = "email: " + email
    testMe = testMe.replacingOccurrences(of: "\n\(emailline)",  with: "")
    print(testMe)
    

    您将获得testMe的以下打印:

    ---
    # Metadata
    title: hum
    author: jecatatu
    ---
    This is more text outside the yaml block
    

    注意作者行,你的目标没有包括它,但你的代码和问题状态也没有你想要摆脱的。希望这有帮助!