使用正则表达式与NSPredicate

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

Use Regex with NSPredicate

问题

# 目的
- 我想使用 `NSPredicate` 来使用正则表达式匹配所有以 "Test" 开头的字符串。
- 我特别想使用 `Regex`  `NSPredicate`

# 问题
1. 我犯了什么错误?
2. 使用正则表达式实现我想做的事情的正确方法是什么?

# 代码 (我的尝试,不起作用)
```swift
let tests = ["Testhello", "Car", "a@b.com", "Test", "Test 123"]
let pattern = "^Test"
let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)

for test in tests {
    let eval = predicate.evaluate(with: test)
    print("\(test) - \(eval)")
}

输出

Testhello - false
Car - false
a@b.com - false
Test - true
Test 123 - false
英文:

Aim

  • Using NSPredicate I would like to use Regex to match all strings beginning with "Test"
  • I specifically want to use Regex and NSPredicate.

Questions

  1. What mistake am I making?
  2. What is the right way to use Regex to achieve what I am trying to do.

Code (My attempt, doesn't work)

let tests = ["Testhello", "Car", "a@b.com", "Test", "Test 123"]
let pattern = "^Test"
let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)

for test in tests {
    let eval = predicate.evaluate(with: test)
    print("\(test) - \(eval)")
}

Output

Testhello - false
Car - false
a@b.com - false
Test - true
Test 123 - false

答案1

得分: 2

NSPredicateMATCHES 中使用的正则表达式必须与整个字符串匹配,因此你需要使用:

let pattern = "Test.*"

或者 - 如果输入字符串中可以有多行:

let pattern = "(?s)Test.*"

以便让 .* 匹配剩余的字符串。

如果字符串必须以 Test 结尾,使用:

let pattern = "(?s).*Test"

在这里不需要使用 ^$ 锚点,因为它们在这里是隐含的。

如果字符串必须包含一个 Test 子字符串,使用:

let pattern = "(?s).*Test.*"

请注意,这不是非常高效的,因为第一个 .* 导致了高度的回溯。

英文:

The regex used with NSPRedicate and MATCHES must match the whole string, so you need to use

let pattern = "Test.*"

Or - if there can be mutliple lines in the input string:

let pattern = "(?s)Test.*"

to let the .* consume the rest of the string.

If the string must end with Test, use

let pattern = "(?s).*Test"

You do not even need the ^ or $ anchors here since they are implicit here.

If the string must contain a Test substring, use

let pattern = "(?s).*Test.*"

Note that this is not efficient though due to high backtracking caused by the first .*.

答案2

得分: 0

尝试精确匹配.... 尝试使用 MATCHES,尝试使用 LIKE 或 CONTAINS 代替。

let predicate = NSPredicate(format: "SELF CONTAINS %@", pattern)

请参阅此处以获取更多信息。

英文:

You try an exact match.... try with MATCHES, try LIKE or CONTAINS instead.

let predicate = NSPredicate(format: "SELF CONTAINS %@", pattern)

See Here as you need

huangapple
  • 本文由 发表于 2023年2月8日 23:02:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387666.html
匿名

发表评论

匿名网友

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

确定