【问题标题】:Why doesn't NSRegularExpression return index of matches?为什么 NSRegularExpression 不返回匹配索引?
【发布时间】:2018-06-12 16:23:12
【问题描述】:

假设我想遍历以下 HTML 以进行正则表达式匹配:

<ul class="product_images">
    <li>
        <a data-style-name="keyword_1">
            <img>
        </a>
    </li>
    <li>
        <a data-style-name="keyword_2">
            <img>
    </a>
    </li>
</ul>

我可以使用Kanna 之类的解析器和NSRegularExpression 之类的块迭代器方法来计算&lt;li&gt; 的每个实例并返回第一个匹配项的索引,然后我可以使用它来模拟鼠标单击像这样的匹配元素:

WKWebView.evaluateJavaScript("document.getElementsByClassName('product_images')[\(keywordIndex)].click()", completionHandler: nil)

但是使用像$("li:contains('keyword_2')") 这样的jQuery 选择器呢?来自 Python 和 JavaScript,我无法适应 Swift 的语法,我觉得我可以使用 jQuery 选择器来压缩我的函数。大多数 threads 建议使用依赖项,但我想知道是否有办法在 Swift 中本地执行此操作 - 也许是 NSSelectorFromString?也就是说,如果任何更精通该语言的人可以为我指出正确的方向,我将非常感谢您的帮助。下面是我的代码示例。实际上,我无法计算每个 &lt;li&gt; 元素的数量;我想点击包含keyword_2的那个。

片段

// Go to parent of match element and count each <li> element

func findKeyword() {
    var keyword = "keyword_2"
    var keywordIndex = 0
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) { 
            self.browserView.evaluateJavaScript("document.getElementsByTagName('html')[0].innerHTML.toString()", completionHandler: { (html: Any?, error: Error?) in
                if let HTML = html as? String {
                    let doc = try? Kanna.HTML(html: HTML, encoding: String.Encoding.utf8)
                    for string in (doc?.css("ul[class^='product_images']/li"))! {
                        if keyword(true, {$0 && string.text!.range(of: $1) != nil}) {
                            print("Found: " + string.text!)
                        }
                        keywordIndex += 1
                    }
                }
            })
    }
}

【问题讨论】:

  • @LeoDabus 好的,所以我会像这样编辑函数的参数:func FindKeyword(options: NSRegularExpression),对吗?
  • @LeoDabus 知道了。我现在如何解决以下错误:Cannot call value of non-function type 'String'?

标签: jquery regex swift cocoa nsregularexpression


【解决方案1】:

解决了问题!问题出在我的 for 循环中——特别是第一行:

for string in (doc?.css("ul[class^='product_images']/li"))! { ...

在这里我使用string,而我应该使用keyword,因为那是我正在寻找的字符串。因此,我按照上面的顺序将string 替换为keyword,一切顺利。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-15
    • 2021-11-19
    • 2018-04-03
    • 2018-04-03
    • 2020-10-19
    • 2014-04-21
    • 2019-01-11
    相关资源
    最近更新 更多