简体   繁体   English

regex.matches 方法匹配和计数错误

[英]The regex.matches method is matching and counting wrongly

In a TextView the user can insert text and images, like a notes.在 TextView 中,用户可以插入文本和图像,就像注释一样。 To save the whole TextView content in the database (Realm), I replaced the image itself for a pattern "[image]imageName[/image]", so when I load back this data to the TextView, I want to replace back this pattern for the images.为了将整个 TextView 内容保存在数据库 (Realm) 中,我将图像本身替换为模式“[image]imageName[/image]”,因此当我将此数据加载回 TextView 时,我想替换回此模式对于图像。 I made this function:我做了这个功能:

let attributedString = NSMutableAttributedString(string: txtNote.text)

        let range = NSRange(location: 0, length: attributedString.string.utf16.count)
        let regex = NSRegularExpression("[image](.*?)[/image]")

        for match in regex.matches(in: attributedString.string, options: [], range: range) {
            if let rangeForImageName = Range(match.range(at: 1), in: attributedString.string){

                let imageName = String(attributedString.string[rangeForImageName])

                if let image = loadImage(named: imageName) {

                    let attachment = NSTextAttachment()
                    attachment.image = image
                    let oldWidth = attachment.image!.size.width;
                    let scaleFactor = (oldWidth / (txtNote.frame.size.width - 10))

                    attachment.image = UIImage(cgImage: attachment.image!.cgImage!, scale: scaleFactor, orientation: .up)

                    let attString = NSAttributedString(attachment: attachment)

                    txtNote.textStorage.insert(attString, at: txtNote.selectedRange.location)
                } else {
                    print("Image not found")
                }
            }
        }

I also have this extension to avoid a try catch in the function above:我也有这个扩展,以避免在上面的函数中尝试捕获:

extension NSRegularExpression {
    convenience init(_ pattern: String) {
        do {
            try self.init(pattern: pattern)
        } catch {
            preconditionFailure("Illegal regular expression: \(pattern).")
        }
    }
}

The example that I'm running, the content on attributedString:我正在运行的示例,attributedString 上的内容:

Like Gorillaz :D
[image]4397ACA6-ADDC-4977-8D67-9FF44F10384A.jpeg[/image]

[image]9BE22CA8-9C6C-4FF9-B46F-D8AF33703061.jpeg[/image]

Etc.{
}

It should be 2 matches, and the image names should be: "4397ACA6-ADDC-4977-8D67-9FF44F10384A.jpeg" and "9BE22CA8-9C6C-4FF9-B46F-D8AF33703061.jpeg".它应该是 2 个匹配项,图像名称应该是:“4397ACA6-ADDC-4977-8D67-9FF44F10384A.jpeg”和“9BE22CA8-9C6C-4FF9-B46F-D8AF33703061.jpeg”。

But my function is returning 14 matches and the image names like: "k", "ll", "", "]4397ACA6-ADDC-4977-8D67-9FF44F10384A.jp", "[", etc.但我的函数返回 14 个匹配项和图像名称,如:“k”、“ll”、“”、“]4397ACA6-ADDC-4977-8D67-9FF44F10384A.jp”、“[”等。

Any idea abou what I'm doing wrong?知道我做错了什么吗? I've been research for some error like this unsuccessfully all day long.我整天都在研究这样的错误,但没有成功。

The [image] and [/image] form character classes that match single chars, the former matching i , m , a , g or e and the latter also matching / . [image][/image]形成匹配单个字符的字符类,前者匹配image ,后者也匹配/

If you want to treat a part of a regex as a literal substring, you may "quote" it with \\Q...\\E operators:如果您想将正则表达式的一部分视为文字子字符串,您可以使用\\Q...\\E运算符“引用”它:

let regex = NSRegularExpression("\\Q[image]\\E(.*?)\\Q[/image]\\E")

If you are sure what you are doing, escape the brackets manually, "\\\\[image\\\\](.*?)\\\\[/image\\\\]" .如果您确定自己在做什么,请手动转义括号"\\\\[image\\\\](.*?)\\\\[/image\\\\]"

See Regular Expression Metacharacters table:请参阅正则表达式元字符表:

\\Q Quotes all following characters until \\E . \\Q引用所有以下字符,直到\\E
\\E Terminates a \\Q ... \\E quoted sequence. \\E终止一个\\Q ... \\E引用的序列。

"Quotes" means "adds backslashes before the special chars to make them match as literal chars" here. “引号”在这里的意思是“在特殊字符之前添加反斜杠,使它们与文字字符匹配”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM