作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用正则表达式在字符串中搜索“-”,然后用项目符号替换它。
如果我的字符串是这样的:
- 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/
我是一名优秀的程序员,十分优秀!