I can't include ' symbol to Regular Expressions

╄→尐↘猪︶ㄣ 提交于 2020-01-11 12:05:11

问题


I try to include ' symbol to Regular Expressions

I use this function

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 []
    }
}

and this Regular Expressions

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

when I search I can find numbers and english letters

but not ' symbol


回答1:


I guess that what you really want is this:

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

Note that I have removed the ^ (text start) and $ (text end) characters because then your whole text would have to match.

I have merged the groups because otherwise you would not match the text as a whole word. You would get separate apostrophe and then the word.

I have changed the character into the proper ' character. The automatic conversion from the simple apostrophe is caused by iOS 11 Smart Punctuation. You can turn it off on an input using:

input.smartQuotesType = .no

See https://developer.apple.com/documentation/uikit/uitextinputtraits/2865931-smartquotestype



来源:https://stackoverflow.com/questions/46162500/i-cant-include-symbol-to-regular-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!