swift - 如何在多行上进行正则表达式搜索?
问题描述
我正在使用正则表达式在字符串中搜索“-”,然后用项目符号替换它。
如果我的字符串是这样的:
- 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)
- 下一个字符必须是空格(但字符没有放入匹配中,因为它是一个前瞻)
推荐阅读
- mysql - 每周查询新用户数 - 如何按年/周排序?
- windows - 建立外部连接以在 Windows 上的 docker 映像上安装 git 时出错
- azure - 在管理组中部署自定义 Azure 策略的选项
- angular - 使用 --prod 标志构建时 AngularFireFunctions 注入错误
- firebase - Firebase:突然无法再部署
- r - 如何在循环中使用 cbind 命名列
- java - `thenRunAsync(...)` 和 `CompletableFuture.runAsync(() -> { ... });` 有关系吗?
- flutter - 在颤动的标签栏的应用栏中添加返回按钮
- c++ - 这种快速排序算法有什么问题?
- f# - F# 序列、列表和数组