提问人:Ian 提问时间:9/13/2023 更新时间:9/13/2023 访问量:34
使用正则表达式将字符行拆分为列
Splitting character row into columns using Regex
问:
我有一个单列数据集,其中每一行都是不同长度的串联字符串。我正在尝试使用正则表达式将每行拆分为 3 列。数据集的示例如下所示。
第 1 列 (ID) 将是字母数字的初始字符串。这始终是相同的长度(在本例中为 24 个字符)
第 2 列(类型)将是中间位。这可能在长度和字符类型(与号、空格、斜杠、逗号,但绝不会因数字)而异
第 3 列(数字)将是字符串-最终数字序列,其长度也是固定的(在本例中为 14)。
c23uij49753dfd3273shdjsh /Animals/Birds/Cardinal 0.873289139232
91873nc9248jfe08jsdif894 /Animals/Mammals/Felines/Tigers 0.989734823872
38939137fhjnffnf73nxlppa /Transportation/Automobiles & Vehicles/Ford-Explorer 0.983947399348
data <- data.frame(
string=c("c23uij49753dfd3273shdjsh /Animals/Birds/Cardinal 0.873289139232",
"91873nc9248jfe08jsdif894 /Animals/Mammals/Felines/Tigers 0.989734823872",
"38939137fhjnffnf73nxlppa /Transportation/Automobiles & Vehicles/Ford-Explorer 0.983947399348"))
我一直在尝试使用 extract(),但无法获得针对中间部分的正则表达式。像下面这样的东西在正确的轨道上,但不能让我到达那里。
output <- extract(data, string, into=c('ID', "Type", "Numerical"), "(.{24)([a-zA-Z]*)(.{14})
答:
1赞
Wiktor Stribiżew
9/13/2023
#1
你可以使用
^(\w{24})\s+(.*?)\s+(\d+\.\d+)$
请参阅正则表达式演示。在 R 代码中,定义为 ."^(\\w{24})\\s+(.*?)\\s+(\\d+\\.\\d+)$"
细节:
^
- 字符串的开头(\w{24})
- 第 1 组:24 个字母数字或下划线字符\s+
- 一个或多个空格(.*?)
- 第 2 组:任何零个或多个字符尽可能少\s+
- 一个或多个空格(\d+\.\d+)
- 第 3 组:一个或多个数字、、一个或多个数字.
$
- 字符串末尾。
评论
output <- str_match(data$string, "^(.{24})([^0-9]+)(.{14}) (.+)$")
output <- str_match(data$string, "^(.{24})([^0-9]+)(.+)$")