Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't include ' symbol to Regular Expressions

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

like image 939
Basil Avatar asked Sep 06 '25 20:09

Basil


1 Answers

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

like image 189
Sulthan Avatar answered Sep 10 '25 12:09

Sulthan