使用Swift 5.7+正则表达式查找字符串中的范围

huangapple go评论79阅读模式
英文:

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) -&gt; Range&lt;Self.Index&gt;?

let range = myString.firstRange(of: /\s*\d+/)

huangapple
  • 本文由 发表于 2023年8月5日 04:18:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定