我有一个可以有两种格式的字符串,
第一种格式:
route-policy testPolicy
if (destination in pfx_manju) then
set extcommunity rt (10429:103) additive
endif
end-policy
第二种格式:
route-policy testPolicy
if (destination in EXP1) then
set extcommunity rt (27699:352002, 2.2.2.2:98) additive
elseif (destination in pfx_manju) then
set extcommunity rt (27699:339600, 27679:339700, 1.1.1.1:6763, 65536:45633) additive
elseif (destination in EXP5) then
drop
endif
end-policy
第三种格式:
route-policy EXPORTRP1
if (destination in EXP1) or (destination in EXP2) then
set extcommunity rt (27699:352002, 2.2.2.2:98) additive
elseif (destination in pfx_manju) or (destination in EXP4) then
set extcommunity rt (27699:339600, 27679:339700, 1.1.1.1:6763, 65536:45633) additive
elseif (destination in EXP5) or (destination in EXP6) then
drop
endif
end-policy
所以这里完整的文本以字符串形式出现。字符串可以是单个条件(if)或多个条件(elseIf 条件)。
我想从上面的字符串中提取一个硬编码策略 (pfx_manju) 的 rt 值。我可以使用下面的正则表达式提取 rt 值,
final String regex = "rt \\(([^)]+)\\)";
现在的问题是,我想提取属于硬编码策略(pfx_manju)的子字符串。
所以条件是获取一个子字符串,起始位置是pfx_manju的索引,结束位置是后续的endif或elseif。
所以我想要上面示例的子字符串输出,如下所述,
第一个子字符串:
pfx_manju) then
set extcommunity rt (10429:103) additive
第二个子字符串:
pfx_manju) then
set extcommunity rt (27699:339600, 27679:339700, 1.1.1.1:6763, 65536:45633) additive
第三个子字符串:
pfx_manju) or (destination in EXP4) then
set extcommunity rt (27699:339600, 27679:339700, 1.1.1.1:6763, 65536:45633) additive
任何乐观解决方案的建议将不胜感激
最佳答案
以下正则表达式应该可以工作
pfx_manju\)[\s\S]*?rt \(([^)]+)\) additive
正则表达式匹配从 pfx_manju
条件开始的字符串一直到 rt
值,这意味着它在只有 pfx_manju
时捕获 rt 值> 条件。如果您使用java,则需要转义,\
。
参见正则表达式demo
关于java - 正则表达式从复杂字符串中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62056095/