gpt4 book ai didi

regex - 如何在R中精确匹配正则表达式并提取模式

转载 作者:行者123 更新时间:2023-12-01 10:33:32 28 4
gpt4 key购买 nike

我想从我的字符串向量中获取模式

string <- c(
"P10000101 - Przychody netto ze sprzedazy produktów" ,
"P10000102_PL - Przychody nettozy uslug",
"P1000010201_PL - Handlowych, marketingowych, szkoleniowych",
"P100001020101 - - Handlowych,, szkoleniowych - refaktury",
"- Handlowych, marketingowych,P100001020102, - pozostale"
)

结果我想得到正则表达式的精确匹配

result <- c(
"P10000101",
"P10000102_PL",
"P1000010201_PL",
"P100001020101",
"P100001020102"
)

我尝试使用此pattern = "([PLA]\\d+)"value = T, fixed = T, perl = T 的不同组合。

grep(x = string, pattern = "([PLA]\\d+(_PL)?)", fixed = T)

最佳答案

我们可以尝试使用 str_extract

library(stringr)
str_extract(string, "P\\d+(_[A-Z]+)*")
#[1] "P10000101" "P10000102_PL" "P1000010201_PL" "P100001020101" "P100001020102"

grep 用于查找匹配模式是否存在于特定字符串中。对于提取,使用 subgregexpr/regmatchesstr_extract

使用base R (regexpr/regmatches)

regmatches(string, regexpr("P\\d+(_[A-Z]+)*", string))
#[1] "P10000101" "P10000102_PL" "P1000010201_PL" "P100001020101" "P100001020102"

基本上,要匹配的模式是 P 后跟一个数字 (\\d+),然后是贪婪 (*) 匹配_ 和一个或多个大写字母。

关于regex - 如何在R中精确匹配正则表达式并提取模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39099107/

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