gpt4 book ai didi

swift - 如何在多行上进行正则表达式搜索?

转载 作者:行者123 更新时间:2023-11-28 05:40:17 24 4
gpt4 key购买 nike

我正在使用正则表达式在字符串中搜索“-”,然后用项目符号替换它。

如果我的字符串是这样的:

- Hello 1

它有效。这是我得到的结果:

 . Hello 1

但是,当我的字符串是这样的时候:

- Hello 1 - Hello 2  
- Hello 3

这是行不通的。这是我得到的:

. Hello 1 - Hello 2
- Hello 3

这是我想要的结果:

. Hello 1 - Hello 2
. Hello 2

这是我正在使用的函数:

    func applyBulletPointsFormat() {
let matches = RegexPattern.bulletPointRegex.matches(mutableString as String)
matches.reversed().forEach { formattedString in
let newRange = NSRange(location: 0, length: 1)
replaceCharacters(in: newRange , with: "\u{2022} ")
}
}

这是我的正则表达式 => "^\-\s(.*)"

这是我在 www.regexr.com => "/^-\s(.*)/gm"上创建的正确正则表达式。我不知道如何应用“/gm”。

如何将多行支持应用于我的正则表达式?

最佳答案

你可以使用

let s = "- Hello 1 - Hello 2\n- Hello 3"
let result = s.replacingOccurrences(of: "(?m)^-(?=\\s)", with: "\u{2022}", options: .regularExpression)
print( result )

输出:

• Hello 1 - Hello 2
• Hello 3

详情

  • (?m) - 开启多行模式
  • ^ - 行首
  • - - 连字符
  • (?=\s) - 下一个字符必须是空格(但该字符未放入匹配项中,因为它是前瞻性的)

关于swift - 如何在多行上进行正则表达式搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57006333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com