【问题标题】:Regex to extract sub string from complex string正则表达式从复杂字符串中提取子字符串
【发布时间】:2020-09-15 06:14:52
【问题描述】:

我有一个可以有两种格式的字符串,

第一种格式:

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的索引,结束位置是随后的endifelseif。 p>

所以我想要上述示例的子字符串输出,如下所述,

第一个子字符串:

  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

任何具有乐观解决方案的建议将不胜感激

【问题讨论】:

  • 是你给的子字符串,你要提取的字符串?
  • 是的..我提到的字符串是我应该提取的
  • Cary Swoveland,是的,String 总是会包含一个带有“prx_manju”的条件,如果字符串不包含“prx_manju”,我不会在这里处理任何事情。

标签: java regex string java-8 substring


【解决方案1】:

以下正则表达式应该可以工作

pfx_manju\)[\s\S]*?rt \(([^)]+)\) additive

正则表达式匹配从pfx_manju 条件一直到rt 值的字符串,这意味着它在只有pfx_manju 条件时捕获rt 值。如果您使用的是 java,则需要 scape,\

见正则表达式demo

【讨论】:

  • 好的,我猜字符串总是有你提到的pfx_manju的条件
  • 更新了所有可能的问题并添加了带有构象的评论
  • 是的,尝试了您的建议。感谢您的时间和投入
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 2013-04-12
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多