首页 > 解决方案 > 正则表达式,stringr - 有正则表达式,不能让它在 R 中工作

问题描述

我有一个数据框,其中包含一个名为“full.path.name”的字段,其中包含 s:///01 GROUP/01 SUBGROUP/~$ 文档名称有空格.docx

01 GROUP 是整个字符串中可变大小的模式。

我想在名为“short.path”的数据框中添加一个新字段,它将包含以下内容

s:///01 组

s:///02 组长名称

我已经设法使用 stringr 提取文件的最后四个字符,我想我应该再次使用 stringr。

这给了我文件扩展名

sfiles$file_type<-as.factor(str_sub(sfiles$Type.of.file,-4))

我去了https://www.regextester.com/ 并得到了这个

 s:///*.[^/]*

作为要使用的正则表达式,所以我在下面尝试了它

sfiles$file_path_short<-as.factor(str_match(sfiles$Full.path.name,regex("s:///*.[^/]*")))

我以为我会得到的是我的数据框中的一个新字段,其中包含 01 GROUP 等我得到 NA

当我尝试这个

sfiles$file_path_short<-str_extract(sfiles$Full.path.name,"[S]")

给我S

我哪里错了?当我使用:https://regexr.com/ 我得到 \d* [AZ]* [AZ]*[^/]

我怎么把它放进去

sfiles$file_path_short<-str_extract(sfiles$Full.path.name,\d* [A-Z]* [A-Z]*[^\/])

让事情发挥作用?

编辑:这里有两种解决方案。解决方案起初不起作用的原因是

  sfiles$Full.path.name 

在某些情况下 > 255。

我做了什么:让 g_t_m 的正则表达式工作

 library(tidyverse)
 #read the file
 sfiles1<-read.csv("H:/sdrive_files.csv", stringsAsFactors = F)

 # add a field to calculate path length and filter out
 sfiles$file_path_length <- str_length(sfiles$Full.path.name)
 sfiles<-sfiles%>%filter(file_path_length <=255)

 # then use str_replace to take out the full path name and leave only the 
   top 
 # folder names

 sfiles$file_path_short <- as.factor(str_replace(sfiles$Full.path.name, " 
 (^.+?/[^/]+?)/.+$", "\\1"))
 levels(sfiles$file_path_short)

[1] "S:///01 组 1"
[2] "S:///02 组 2"
[3] "S:///03 组 3"
[4] "S:///04 组4"
[5] "S:///05 第 5 组"
[6] "S:///06 第 6 组"
[7] "S:///07 第 7 组

我认为是引起问题的 full.path.name 字段。为了使 Wiktor 的回答起作用,我这样做了:

#read the file
sfiles<-read.csv("H:/sdrive_files.csv", stringsAsFactors = F)
str(sfiles)       
sfiles$file_path_length <- str_length(sfiles$Full.path.name)
sfiles<-sfiles%>%filter(file_path_length <=255)
sfiles$file_path_short <- str_replace(sfiles$Full.path.name, " 
(^.+?/[^/]+?)/.+$", "\\1")

标签: rregexstringr

解决方案


您可以只使用

sfiles$file_path_short <- str_extract(sfiles$Full.path.name, "^s:///[^/]+")

如果您打算s:///从结果中排除,请将其包装在积极的后视中:

"(?<=^s:///)[^/]+"

查看正则表达式演示

细节

  • ^- 字符串的开始
  • s:///- 文字子串
  • [^/]+- 一个否定字符类,匹配除 . 之外的任何 1+ 个字符/
  • (?<=^s:///)- 一个正向的lookbehind,它需要在s:///当前位置左侧的字符串的开头存在(但这个值不会出现在结果匹配中,因为lookarounds是非消耗模式)。

推荐阅读