我在同一列中有项目代码和说明。项目代码可以包含字母、数字、空格和特殊字符。说明总是以至少4个字母开头。所以我想在4个字母开始的空格处拆分列。我将文本字段转换为小写
x <- c('1234 (a)-b free vacation to aruba',
'1234:43-1b free set of dishes')
理想情况下,这将产生:
itemCode itemDesctiption
1234 (a)-b free vacation to aruba
1234:43-1b free set of dishes
我试过用空格分开
[c('a', 'b', 'c', 'd', 'e', 'f')] <- str_split_fixed(x, ' ', 6)
当然,由于空格有时候是嵌入的,所以它不能给予我想要的。
我回顾了类似的问题,这是接近,但不完全是我要找的。
3条答案
按热度按时间pvabu6sv1#
你可以在base R中使用
strsplit
来实现这一点,并使用一个前瞻来获得项目代码,然后使用sub
从原始字符串中删除项目代码来获得描述:有一个小小的警告,
[a-z]{4}
只有在前4个字母不包含该集合中标准26个符号之外的字母(例如,重音字母)时才能工作。创建于2023年1月21日,使用reprex v2.0.2
cygmwpex2#
请使用
str_extract
检查以下代码创建于2023年1月21日,使用reprex v2.0.2
js81xvg63#
此解决方案基于
tidyr
的函数extract
:regex
的工作原理:基本上,x
中的串被分成两个捕获组,这两个捕获组包含要被提取到两个新列中的内容:(.*[()0-9abc-])
:第1个捕获组;在这里,我们Assert组以括号、数字、破折号或a
、b
或c
中的任何一个结束(请根据需要进行修改!)\\s
:一个空白(未捕获)([a-z]{4,}\\s.*)
:第二个捕获组。这里我们Assert必须至少有4个小写字母,后跟一个空格和更多字符编辑1:
结帐:
regex = "([()0-9a-z-]+)[\\s-]+(.*)"
似乎也有效!
编辑2:
基于
itemCode
从不被空白中断的观察,这也起作用:regex = "(\\S+)[\\s-]+(.*)"