我不能在正则表达式中包含'符号

时间:2017-09-11 18:48:21

标签: swift string ios11 swift4

我尝试将'符号包含在正则表达式

我使用此功能

func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)
        let results = regex.matches(in: text,
                                    range: NSRange(text.startIndex..., in: text))
        return results.map {
            text.substring(with: Range($0.range, in: text)!)
        }
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

和这个正则表达式

    let matched = matches(for: "^[‘]|[0-9]|[a-zA-Z]+$", in: string)

当我搜索时,我可以找到数字和英文字母

但不是'符号

1 个答案:

答案 0 :(得分:6)

我猜你真正想要的是这个:

"['0-9a-zA-Z]+"

请注意,我删除了^(文字开头)和$(文字结尾)字符,因为这样您的整个文字就必须匹配。

我已将这些组合并,因为否则您将不会将文本与整个单词匹配。你会得到单独的撇号,然后是单词。

我已将字符更改为正确的'字符。简单撇号的自动转换是由iOS 11 Smart Punctuation引起的。您可以使用以下命令将输入​​关闭:

input.smartQuotesType = .no

请参阅https://developer.apple.com/documentation/uikit/uitextinputtraits/2865931-smartquotestype