【问题标题】:Regular expression to remove link in String in Swift [duplicate]在 Swift 中删除字符串中的链接的正则表达式 [重复]
【发布时间】:2019-08-31 11:45:02
【问题描述】:

我有一堆从服务收到的字符串,需要更改文本以提取和删除下面提到的 3 种类型的链接

anchor - [anchor:info]Account Details[/anchor]
action -  [action:contact]Contact info[/anchor]
link-to - [link-to:register]Create An Account[/link-to]

来自服务的完整长度文本示例:

  1. “您的[anchor:info]Account Details[/anchor] 有问题。”
  2. “您的[anchor:rewards]Sign Up For Rewards[/anchor] 有问题。”
  3. “我们无法识别此帐户。请重新输入您的电子邮件或[link-to:register]Create An Account[/link-to]。”

而预期的结果应该是:

  1. “您的帐户详细信息有问题。”
  2. “您的注册奖励有问题。”
  3. “我们无法识别此帐户。请重新输入您的电子邮件或创建一个帐户。”

我想我会使用 replaceOccurrences 函数来实现这一点。但是我还没有破解我所需格式的正则表达式。

let aString = "There's a problem with your [anchor:info]Account Details[/anchor]."
let newString = aString.replacingOccurrences(of: "regex here", with: " ", options: .regularExpression, range: nil)

我可以有 3 个单独的正则表达式来匹配这 3 个案例,或者有一个可以处理以下情况的正则表达式:

[any_link_type:any_identifier]Any Text[/any_link_type]

一些正则表达式专家可以帮助我吗?

【问题讨论】:

    标签: ios swift regex macos nsregularexpression


    【解决方案1】:

    知道了 :) 这个正则表达式可以满足我的要求:\[.*?\]

    let linkString = "We didn't recognize this account. Please re-enter your email or [link-to:register]Create An Account[/link-to]."
    
    let newLinkString = linkString.replacingOccurrences(of: "\\[.*?\\]", with: "", options: .regularExpression, range: nil)
    

    【讨论】:

      【解决方案2】:

      试试这个模式^([^[]+)\[([^:\]]+)[^\]]*\]([^[]+)\[\/\2\]

      并将其替换为\1\3

      解释:

      ^ - 字符串的开头

      ([^[]+) - 匹配除[ 之外的一个或多个字符并存储在捕获组中

      \[ - 匹配 [ 字面意思

      ([^:\]]+) - 匹配除:] 之外的一个或多个字符并存储在捕获组中

      [^\]]* - 匹配除]之外的零个或多个字符

      \] - 匹配 ] 字面意思

      ([^[]+) - 匹配[以外的一个或多个字符并存储在捕获组中

      \[\/ - 匹配 [/ 字面意思

      \2 - 匹配第二个捕获组中匹配的相同文本(因此它匹配结束标记,如anchor

      \] - 匹配 ] 字面意思

      Demo

      【讨论】:

        【解决方案3】:

        使用以下代码获得预期的输出。

        Swift 4:-

        let aString = "There's a problem with your [anchor:info]Account Details[/anchor]."
        let newString = aString.replacingOccurrences(of: "\\[.*?\\]", with: "", options: .regularExpression, range: nil)
        print(newString) //There's a problem with your Account Details.
        

        Swift 5:-

        let aString = "There's a problem with your [anchor:info]Account Details[/anchor]."
        let newString = aString.replacingOccurrences(of: #"\[.*?\]"#, with: " ", options: .regularExpression, range: nil)
        print(newString) //There's a problem with your Account Details.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-23
          • 2010-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-14
          • 2018-01-26
          相关资源
          最近更新 更多