我试图从分隔字符串中解析单词,并按顺序排列捕获组。例如
dog.cat.chicken.horse.whale
我知道([^.]+)可以解析出每个单词,但这会将每个字符串放入捕获组1中。
Match 1
Full match 0-3 `dog`
Group 1. 0-3 `dog`
Match 2
Full match 4-7 `cat`
Group 1. 4-7 `cat`
Match 3
Full match 8-15 `chicken`
Group 1. 8-15 `chicken`
Match 4
Full match 16-21 `horse`
Group 1. 16-21 `horse`
Match 5
Full match 22-27 `whale`
Group 1. 22-27 `whale`我真正需要的是
Match 1
Full match 0-27 `dog.cat.chicken.horse.whale`
Group 1. 0-3 `dog`
Group 2. 4-7 `cat`
Group 3. 8-15 `chicken`
Group 4. 16-21 `horse`
Group 5. 22-27 `whale`我尝试过多次迭代,但没有成功,有人知道怎么做吗?
发布于 2018-01-12 22:09:39
这个案子没有很好的解决办法。您可以做的就是添加可选的非捕获群和捕获的,以说明某些组的数量。
所以,看起来
([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)(?:\.([^.]+))?(?:\.([^.]+))?(?:\.([^.]+))?以此类推,只需添加更多的(?:\.([^.]+))?,直到达到应该定义的极限为止。
见regex演示。
请注意,您可能希望锚定模式以避免部分匹配:
^([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)(?:\.([^.]+))?(?:\.([^.]+))?(?:\.([^.]+))?$^与字符串的开头匹配,而$则断言字符串末尾的位置。
https://stackoverflow.com/questions/48231613
复制相似问题