正则表达式,用于在标记内部转换括号和嵌套括号

Pho*_*nix 1 java regex

我想写一个正则表达式,可以删除围绕[分]的括号

String input1 = "this is a [cent] and [cent] string" 
String output1 = "this is a cent and cent string" 
Run Code Online (Sandbox Code Playgroud)

但如果它嵌套如下:

String input2="this is a [cent[cent] and [cent]cent] string"
String output2="this is a cent[cent and cent]cent string"
Run Code Online (Sandbox Code Playgroud)

我只能在字符串上使用replaceAll,所以如何在下面的代码中创建模式?更换字符串应该是什么?

Pattern rulerPattern1 = Pattern.compile("", Pattern.MULTILINE);
System.out.println(rulerPattern1.matcher(input1).replaceAll(""));
Run Code Online (Sandbox Code Playgroud)

更新:嵌套括号格式正确,只有两个级别,如案例2.

编辑:如果这是字符串"[<centd>[</centd>]purposes[<centd>]</centd>]"; 那么OUPTUT应该是<centd>[</centd> purposes <centd>]</centd>..基本上如果括号在centd开头和结束之间留在那里或者删除

Ro *_* Mi 6

描述

该正则表达式将基于仅在支架的一侧上具有空间来替换括号.

正则表达式: (?<=\s)[\[\]](?=\S)|(?<=\S)[\[\]](?=\s)

用空字符串替换

在此输入图像描述

摘要

  1. 样品1
    • 输入: this is a [cent[cent] and [cent]cent] string
    • 产量 this is a cent[cent and cent]cent string
  2. 样本2
    • 输入: this is a [cent[cent] and [cent]cent] string
    • 产量 this is a cent[cent and cent]cent string
  3. 样本3
    • 输入: [<cent>[</cent>] and [<cent>]Chemotherapy services.</cent>]
    • 产量 [<cent>[</cent> and <cent>]Chemotherapy services.</cent>]

要解决问题的编辑,该表达式将找到:

  • [<centd>[</centd>] 并用它替换它们 <centd>[</centd>
  • [<centd>]或者[</centd>],只删除外方括号
  • 保留所有其他方括号

正则表达式: \[(<centd>[\[\]]<\/centd>)\]|\[(<\/?centd>)\]

用...来代替: $1$2

在此输入图像描述

  1. 样本4
    • 输入: [<centd>[</centd>]purposes[<centd>]</centd>]
    • 产量 <centd>[</centd>pur [T] poses<centd>]</centd>