Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex R中的Excel正则表达式函数_Regex_R_Excel - Fatal编程技术网

Regex R中的Excel正则表达式函数

Regex R中的Excel正则表达式函数,regex,r,excel,Regex,R,Excel,我经常使用Excel工作表,其中一些字段(观察值)以部分结构化形式包含大量文本内容(至少在视觉上) 因此,单个单元格/Obs的内容可能类似于: My name is John Doe I live at my address My Post code is ABC123 My Favorite Pet is: A dog 在Excel中,我创建了一些函数,我可以使用这些函数在单元格中查找字符串,让我们假设数据在“A1”中 在“A2”中,我可以使用“=GETPOSTCODE(A1),其中函数为:

我经常使用Excel工作表,其中一些字段(观察值)以部分结构化形式包含大量文本内容(至少在视觉上)

因此,单个单元格/Obs的内容可能类似于:

My name is John Doe
I live at my address
My Post code is ABC123
My Favorite Pet is: A dog
在Excel中,我创建了一些函数,我可以使用这些函数在单元格中查找字符串,让我们假设数据在“A1”中 在“A2”中,我可以使用“=GETPOSTCODE(A1),其中函数为:

Function GetPostCode(PostCode As Range) As String
regex.Pattern = "[A-Z]{3}\d{3,}\b\w*"
regex.IgnoreCase = True
regex.MultiLine = True
Set X = regex.Execute(PostCode.Value)
For Each x1 In X
GetPostCode = UCase(x1)
Exit For
Next
End Function
我可以在r中使用什么样的结构/功能来实现这一点? 这些单元格实际上包含的数据远不止这些,纯粹是举个例子,我有很多不同的“get”函数和不同的正则表达式

我已经很好地了解了所有Grep类型的命令,但是我正在努力提高有限的/R技能

我一直在围绕这一原则工作,但几乎停滞了(其中textfield显然是包含我文本的列!)我可以得到一个包含post代码的所有行的列表,而不仅仅是post代码:

df$postcode <- df[(df$textfield = grep("[A-Z]{3}\\d{3,}\\b\\w*", df$textfield), ]

df$postcode我认为您需要结合
regexpr
grepexpr
(查找字符串中的匹配项)和
regmatches
来提取字符串的匹配部分:

x <- "My name is John Doe
I live at my address
My Post code is ABC123
My Favorite Pet is: A dog"

> regmatches(x, regexpr("[A-Z]{3}\\d{3,}\\b\\w*", x, ignore.case = TRUE))
[1] "ABC123"
x regmatches(x,regexpr([A-Z]{3}\\d{3,}\\b\\w*”,x,ignore.case=TRUE))
[1] “ABC123”
其他选项可能包括来自stringr的
str_extract
或来自stringi软件包的
stri_extract