我不能在正则表达式中包含'符号 [英] I can't include ' symbol to Regular Expressions

查看:57
本文介绍了我不能在正则表达式中包含'符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在正则表达式中添加'符号

I try to include ' symbol to Regular Expressions

我使用此功能

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)

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

when I search I can find numbers and english letters

但不是'符号

推荐答案

我想您真正想要的是这样:

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.

我已将'字符更改为正确的'字符.从简单的撇号自动转换是由iOS 11智能标点符号引起的.您可以使用以下命令在输入中将其关闭:

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

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

这篇关于我不能在正则表达式中包含'符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆