【问题标题】:Cannot find Substring "n't"找不到子字符串“n't”
【发布时间】:2018-03-12 00:14:57
【问题描述】:

我正在尝试确定输入字符串是否包含“n't”或“not”。 例如,如果输入是:

let part = "Hi, I can't be found!" 

我想找到否定的存在。 我尝试过 input.contains、.range 和 NSRegularExpression。所有这些都成功找到了“not”,但没有找到“n't”。我也尝试过逃避角色。

'//REGEX:

let negationPattern = "(?:n't|[Nn]ot)"
do {
    let regex = try NSRegularExpression(pattern: negationPattern)
    let results = regex.matches(in: text,range: NSRange(part.startIndex..., in: part))
    print("results are \(results)")
    negation = (results.count > 0)

} catch let error {
    print("invalid regex: \(error.localizedDescription)")
}

//.CONTAINS
if part.contains("not") || part.contains("n't"){
    print("negation present in part")
    negation = true
}

//.RANGE (showing .regex option; also tried without)
if part.lowercased().range(of:"not", options: .regularExpression) != nil || part.lowercased().range(of:"n't", options: .regularExpression) != nil {
    print("negation present in part")
    negation = true
}

这是一张图片:

【问题讨论】:

  • 请不要使用您已经尝试过的代码的屏幕截图 - 直接在您的问题中添加代码。
  • 谢谢。有什么想法吗?

标签: swift string substring


【解决方案1】:

这有点棘手,实际上是屏幕截图泄露了它:您的正则表达式模式中有一个普通的单引号,但输入文本中有一个“智能”或“卷曲”撇号。区别很微妙:

  • 常规:'
  • 聪明:'

当他们认为合适时,许多文本字段会自动将常规单引号替换为“智能”撇号。然而,你的正则表达式只匹配普通的单引号,这个小测试证明了这一点:

func isNegation(input text: String) -> Bool {
    let negationPattern = "(?:n't|[Nn]ot)"
    let regex = try! NSRegularExpression(pattern: negationPattern)
    let matches = regex.matches(in: text,range: NSRange(text.startIndex..., in: text))
    return matches.count > 0
}

for input in ["not", "n't", "n’t"] {
    print("\"\(input)\" is negation: \(isNegation(input: input) ? "YES" : "NO")")
}

打印出来:

"not" is negation: YES
"n't" is negation: YES
"n’t" is negation: NO

如果您想继续使用正则表达式来解决这个问题,您需要修改它以匹配这种标点符号,并避免假设您的所有输入文本都包含“纯”单引号。

【讨论】:

  • 谢谢!我已将 textField 输入的 smartQuotes 设置为 .no,它可以工作。再次感谢:)
猜你喜欢
  • 1970-01-01
  • 2012-08-20
  • 2022-01-14
  • 2019-11-19
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
相关资源
最近更新 更多