gpt4 book ai didi

regex - 字符串,str_extract : how to do positive lookbehind?

转载 作者:行者123 更新时间:2023-12-02 04:17:43 26 4
gpt4 key购买 nike

很简单的问题。我只需要使用正则表达式正向查找捕获一些字符串,但我没有找到一种方法来做到这一点。

这是一个例子,假设我有一些字符串:

library(stringr)
myStrings <- c("MFG: acme", "something else", "MFG: initech")

我想提取以“MFG:”为前缀的单词

> result_1  <- str_extract(myStrings,"MFG\\s*:\\s*\\w+")
>
> result_1
[1] "MFG: acme" NA "MFG: initech"

几乎可以做到这一点,但我不想包含“MFG:”部分,所以这就是“积极的向后查找”的用途:

> result_2  <- str_extract(myStrings,"(?<=MFG\\s*:\\s*)\\w+")
Error in stri_extract_first_regex(string, pattern, opts_regex = attr(pattern, :
Look-Behind pattern matches must have a bounded maximum length. (U_REGEX_LOOK_BEHIND_LIMIT)
>

它提示需要“有界最大长度”,但我不知道在哪里指定。如何进行积极的事后工作?确切地说,我可以在哪里指定这个“有界最大长度”?

最佳答案

您需要使用str_match,因为“lookbehind”的模式是文字,并且您只是不知道空格的数量:

> result_1  <- str_match(myStrings,"MFG\\s*:\\s*(\\w+)")
> result_1[,2]
##[1] "acme" NA "initech"

您需要的结果将在第二列中。

请注意,此处不能使用 str_extract,因为该函数会删除捕获的值。

还有一个好处:在 ICU 正则表达式中,lookbehind 不是无限宽度,而是约束宽度。所以,这也行得通:

> result_1  <- str_extract(myStrings,"(?<=MFG\\s{0,100}:\\s{0,100})\\w+")
> result_1
[1] "acme" NA "initech"

关于regex - 字符串,str_extract : how to do positive lookbehind?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35804379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com