【发布时间】:2019-07-18 09:45:30
【问题描述】:
假设我有一个正则表达式
let regexString = "\\s{1,3}(---+)\\s*"
let regex = try? NSRegularExpression(pattern: regexString)
还有一个字符串
let string = "Space --- the final frontier --- these are the voyages..."
让我们进一步假设该字符串确实很长,并且在省略号 (...) 之后延续了数千个字符。
现在我想找到正则表达式 regex 的第一个匹配项,但出于效率原因,我想在某个索引后停止搜索。
示例:
index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
string: S p a c e - - - t h e f i n a l f r o n t i e r
range: + + + + + + + + + + + + + + + ⬆︎ - - - - - - - - - - - -
max
这意味着我只在字符串中搜索一个正则表达式匹配开始在索引15之前。
上述行为与仅搜索字符串的子范围不同。原因如下:
✅ 应该匹配:
以下示例应在 [5–9] 范围内产生匹配,因为匹配在最大索引 (= 7) 之前开始。
index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
string: S p a c e - - - t h e f i n a l f r o n t i e r
range: + + + + + + + ⬆︎ - - - - - - - - - - - - - - - - - - - -
max
❎ 应该,但不匹配:
如果我只搜索到最大索引 (= 7) 的子字符串,正则表达式将无法匹配,因为部分匹配会被截断。
index: 0 1 2 3 4 5 6 7
string: S p a c e - -
range: + + + + + + + ⬆︎
max
我怎样才能做到这一点?
【问题讨论】:
-
firstMatch函数呢? developer.apple.com/documentation/foundation/… -
用
\A.{0,15}?或\A.{0,7}?或任何限制作为前缀
标签: swift regex string nsregularexpression