gpt4 book ai didi

括号内的正则表达式匹配

转载 作者:行者123 更新时间:2023-12-03 09:27:02 25 4
gpt4 key购买 nike

我正在尝试使用一些为 Python 编写的正则表达式也适用于 R。

这是我在 Python 中的内容(使用出色的 re 模块),其中包含我预期的 3 个匹配项:

import re
line = 'VARIABLES = "First [T]" "Second [L]" "Third [1/T]"'
re.findall('"(.*?)"', line)
# ['First [T]', 'Second [L]', 'Third [1/T]']

现在使用 R,这是我最好的尝试:

line <- 'VARIABLES = "First [T]" "Second [L]" "Third [1/T]"'
m <- gregexpr('"(.*?)"', line)
regmatches(line, m)[[1]]
# [1] "\"First [T]\"" "\"Second [L]\"" "\"Third [1/T]\""

为什么 R 匹配整个模式,而不是只匹配括号内的模式?我期待的是:

[1] "First [T]"   "Second [L]"  "Third [1/T]"

此外,perl=TRUE 没有任何区别。可以安全地假设 R 的正则表达式不考虑仅匹配括号,还是我缺少一些技巧?


解决方案摘要:感谢@flodel,它似乎也适用于其他模式,因此它似乎是一个很好的通用解决方案。使用输入字符串 line 和正则表达式模式 pat 的解决方案的紧凑形式是:

pat <- '"(.*?)"'
sub(pat, "\\1", regmatches(line, gregexpr(pat, line))[[1]])

此外,如果在 pat 中使用 PCRE 功能,则应将 perl=TRUE 添加到 gregexpr 中。

最佳答案

如果您打印 m,您将看到 gregexpr(..., perl = TRUE) 为您提供 a) 完整模式的匹配位置和长度包括前引号和结束引号以及 b) 捕获的 (.*).

不幸的是,当regmatches使用m时,它使用前者的位置和长度。

我能想到两种解决方案。

通过sub传递最终输出:

line <- 'VARIABLES = "First [T]" "Second [L]" "Third [1/T]"'
m <- gregexpr('"(.*?)"', line, perl = TRUE)
z <- regmatches(line, m)[[1]]
sub('"(.*?)"', "\\1", z)

或者使用 substring 使用捕获表达式的位置和长度:

start.pos <- attr(m[[1]], "capture.start")
end.pos <- start.pos + attr(m[[1]], "capture.length") - 1L
substring(line, start.pos, end.pos)

为了加深您的理解,请看看如果您的模式 try catch 多个事物会发生什么。另请注意,您可以为捕获组指定名称(文档将其称为Python 样式命名捕获),此处为“capture1”“capture2” :

m <- gregexpr('"(?P<capture1>.*?) \\[(?P<capture2>.*?)\\]"', line, perl = TRUE)
m

start.pos <- attr(m[[1]], "capture.start")
end.pos <- start.pos + attr(m[[1]], "capture.length") - 1L

substring(line, start.pos[, "capture1"],
end.pos[, "capture1"])
# [1] "First" "Second" "Third"

substring(line, start.pos[, "capture2"],
end.pos[, "capture2"])
# [1] "T" "L" "1/T"

关于括号内的正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18347743/

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