【问题标题】:How to insert a substring before/after another substring? [duplicate]如何在另一个子字符串之前/之后插入一个子字符串? [复制]
【发布时间】:2020-08-25 12:05:10
【问题描述】:

假设我们有字符串"asd as asdsd",我需要在"asd"之前和之后插入"<*>",所以结果应该是:"<*>asd<*> as <*>asd<*>sd"

插入应该不区分大小写,所以如果目标是"ASD",结果是一样的:"<*>asd<*> as <*>asd<*>sd"

我试过了

a.insert(contentsOf: separator, at: a.range(of: "asd", options: .caseInsensitive)!.upperBound)
a.insert(contentsOf: separator, at: a.range(of: "asd", options: .caseInsensitive)!.lowerBound)

但分隔符只插入"asd"的第一次出现

【问题讨论】:

  • "<*>" + "asd" + "<*>" 代替"asd" 怎么样?你可以使用a = a.replacingOccurrences(of: "asd", with: "<*>$0<*>", options: [.caseInsensitive, .regularExpression])?
  • @Larme 这确实有效,$0. regularExpression 做到了,谢谢!
  • @Larme 我认为您应该将其发布为答案。
  • @Alladinian 当已经有其他问题时 stackoverflow.com/questions/52400793/… stackoverflow.com/questions/61010309/… 等。好的“想法”替换整个而不是两次,因为上限/下限更难。跨度>

标签: swift string


【解决方案1】:

注意:此解决方案是在 OP 提到不区分大小写要求之前发布的。 Larme 的评论实际上包含了这样一个解决方案:

replacingOccurrences(of: "asd", with: "<*>$0<*>", options: [.caseInsensitive, .regularExpression])

如果他将此作为答案发布,请随时接受。


这是一个可能的解决方案:

extension String {
    func enclosing(_ match: String, in tag: String) -> String {
        self.replacingOccurrences(of: match, with: tag + match + tag)
    }
}

let text = "asd as asdsd"
print(text.enclosing("asd", in: "<*>")) 
// Outputs: <*>asd<*> as <*>asd<*>sd

【讨论】:

  • 我想过,但是插入应该是不区分大小写的,所以如果目标是"ASD",结果应该是一样的:"&lt;*&gt;asd&lt;*&gt; as &lt;*&gt;asd&lt;*&gt;sd",但是使用这个解决方案,结果将是"&lt;*&gt;ASD&lt;*&gt; as &lt;*&gt;ASD&lt;*&gt;sd"
猜你喜欢
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 2015-12-08
  • 2014-07-17
相关资源
最近更新 更多