英文:
Find range in a string using Swift 5.7+ Regex
问题
以下是用Swift中的传统方法搜索字符串中的正则表达式并返回找到的范围(如果未找到则返回nil):
let range = myString.range(of: "\\s*\\d+", options: [.regularExpression])
不幸的是,正则表达式字符串 \\s*\\d+
需要在运行时编译,并需要特殊的转义(例如,\\s
而不仅仅是 \s
)。
要升级以使用现代的 Swift 5.7+ 正则表达式字面量,你可以写类似于以下的代码:
let range = myString.range(of: /\s*\d+/)
(我不想使用传统的NSRegularExpression方法。)
英文:
Here is a legacy way in Swift to search a string for a regular expression and return the range where it was found (or nil if not found):
let range = myString.range(of: "\\s*\\d+", options: [.regularExpression])
Unfortunately, the regular expression string "\\s*\\d+"
needs to be compiled at runtime and needs special escaping (for example, \\s
instead of just \s
).
How can I upgrade this to use modern Swift 5.7+ Regex literals? Essentially I want to write something like:
let range = myString.range(of: /\s*\d+/)
(I do not want to use legacy NSRegularExpression methods.)
答案1
得分: 1
You need to use the related method called firstRange(of:)
func firstRange(of regex: some RegexComponent) -> Range<Self.Index>?
let range = myString.firstRange(of: /\s*\d+/)
英文:
You need to use the related method called firstRange(of:)
func firstRange(of regex: some RegexComponent) -> Range<Self.Index>?
let range = myString.firstRange(of: /\s*\d+/)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论