Ric*_*ald 6 regex regex-group prometheus
我正在尝试从分隔的字符串中解析出单词,并按顺序排列捕获组.例如
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`
Run Code Online (Sandbox Code Playgroud)
我真正需要的是类似的东西
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`
Run Code Online (Sandbox Code Playgroud)
我尝试了多次迭代但没有成功,有谁知道怎么做?
对于这种情况没有好的解决办法。您可能要做的就是添加可选的非捕获组和捕获组,以说明一定数量的组。
所以,它可能看起来像
([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)(?:\.([^.]+))?(?:\.([^.]+))?(?:\.([^.]+))?
Run Code Online (Sandbox Code Playgroud)
等等,只需添加更多,(?:\.([^.]+))?
直到达到您应该定义的某个限制。
请参阅正则表达式演示。
请注意,您可能希望锚定模式以避免部分匹配:
^([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)(?:\.([^.]+))?(?:\.([^.]+))?(?:\.([^.]+))?$
Run Code Online (Sandbox Code Playgroud)
匹配^
字符串的开头并$
断言字符串末尾的位置。