java - 正则表达式从复杂字符串中提取子字符串

标签 java regex string java-8 substring

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

第一种格式:

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

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

第一个子字符串:

  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/

相关文章:

java - 读取其中的xml文件和xml文件的链接并继续解析

java - 带有注释为 `@RegisterExtension` 的字段的 JUnit 5 测试在 Kotlin 中不起作用

regex - 必要时使用正则表达式向 csv 文件添加逗号

linux - 在文件中的匹配字符串(模式 1)上方打印特定单词直到匹配字符串(模式 2)

java - 无法解析java中字符串中的字符

java - 提交后未显示更改 (Heroku Java)

java - Eclipse CDT : How to write to . cproject 文件并读回

c# - SQL 查询的正则表达式给出空的 MatchCollection

r - 如何优雅地跨越多个列进行 str_detect 并有条件地填充新列

python - 将列表转换为字符串列表