使用 Notepad++、Regex 重构 CSV 数据

Restructure CSV data with Notepad++, Regex

我有一个包含以下 headers 和(示例)数据的 CSV 文件:

StopName,RouteName,Travel_Direction,Latitude,Longitude
StreetA @ StreetB,1 NameA,DirectionA,Lat,Long
StreetC @ StreetD,1 NameA,DirectionA,Lat,Long
...
StreetE @ StreetF,1 NameA,DirectionB,Lat,Long
StreetG @ StreetH,1 NameA,DirectionB,Lat,Long
...
StreetI @ StreetJ,2 NameB,DirectionC,Lat,Long
StreetK @ StreetL,2 NameB,DirectionC,Lat,Long
...
StreetM @ StreetN,2 NameB,DirectionD,Lat,Long
StreetO @ StreetP,2 NameB,DirectionD,Lat,Long
.
.
.

我想使用正则表达式(目前在 Notepad++ 中)得到以下结果:

1 NameA - DirectionA=[[StreetA @ StreetB,[Lat,Long]], [StreetC @ StreetD,[Lat,Long]], ...]
1 NameA - DirectionB=[[StreetD @ StreetE,[Lat,Long]], [StreetF @ StreetG,[Lat,Long]], ...]
2 NameB - DirectionC=[[StreetH @ StreetI,[Lat,Long]], [StreetJ @ StreetK,[Lat,Long]], ...]
2 NameB - DirectionD=[[StreetL @ StreetM,[Lat,Long]], [StreetN @ StreetO,[Lat,Long]], ...]
.
.
.

使用正则表达式和替换,

RgX: ^([^,]*),([^,]*),([^,]*),(.*)
Sub:  - =[,[]]

Demo: https://regex101.com/r/gS9hD6/1

我已经走到这一步了:

1 NameA - DirectionA=[StreetA @ StreetB,[Lat,Long]]
1 NameA - DirectionA=[StreetC @ StreetD,[Lat,Long]]
1 NameA - DirectionB=[StreetE @ StreetF,[Lat,Long]]
1 NameA - DirectionB=[StreetG @ StreetH,[Lat,Long]]
2 NameB - DirectionC=[StreetI @ StreetJ,[Lat,Long]]
2 NameB - DirectionC=[StreetK @ StreetL,[Lat,Long]]
2 NameB - DirectionD=[StreetM @ StreetN,[Lat,Long]]
2 NameB - DirectionD=[StreetO @ StreetP,[Lat,Long]]

在一个新的正则表达式中,我尝试在“=”上拆分上面的结果,但不知道从那里去哪里。

我认为获得所需结果的一种方法是保留“=”之前的第一个唯一实例,将新行替换为“,”并用 [..] 将其括起来以使其成为数组形式.

编辑: 大约有 10k 个停靠点(总计),但只有大约 100 条独特的路线。

编辑2:(可能我现在要求的改动太多了)

对于第一个正则表达式:

在第二次正则表达式替换开始时,

步骤

1。第一次替换:

  • 查找内容:^([^,]*),([^,]*),([^,]*),(.*)
  • 替换为: - =[[,[]]]
  • 全部替换

2。第二次替换:

  • 查找内容:^[\S\s]*?^([^][]*=)\[\[.*\]\]\K\]\R\[(.*)\]$
  • 替换为:, ]
  • 全部替换

3。重复步骤 2 直到不再出现。

  • 这意味着如果同一个键(路线 - 方向对)有 100 个实例(停靠站),您将必须单击 全部替换 7 次(ceiling(log2(N))).

描述

我在第 1 步中修改了您的正则表达式,以添加一对额外的括号来括起整个集合。

对于步骤 2,它找到一对相同 方向 的线,将最后一条附加到前一条。

^[\S\s]*?^([^][]*=)     #Group 1: captures "1 NameA - DirA="
\[\[.*\]\]              #matches the set of Stops - "[[StA @ StB,[Lat,Long]], ..."
\K                      #keeps the text matched so far out of the match
\]\R                    #closing "]" and newline
                      #match next line (if the same route)
\[(.*)\]$               #and capture the Stop (Group 2)

regex101 Demo for step 1
regex101 Demo for step 2

试试这个 我用手机记事本查了没有错

查找内容:

(s.+@\s\w+),(\d{1,} \w+),(\w+),(.+)

替换为:

 - =[[,[],...]]