首页 > 解决方案 > 如何在多行上进行正则表达式搜索?

问题描述

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

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

- 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”。

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

标签: swiftregex

解决方案


您可以使用

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)- 下一个字符必须是空格(但字符没有放入匹配中,因为它是一个前瞻)

推荐阅读