替换字符串REGEX中的某些字符

时间:2018-07-21 21:10:21

标签: java regex design-patterns replace

我试图替换仅在括号内出现的某些字符,这是我需要替换字符的模式:

Z应该变成布尔

J应该替换为短

L应替换为长

我应该替换为

S应替换为字符串

B应该替换为字节

以下是我的正则表达式的行为示例:

输入:net.sourceforge.ganttproject.shape.PaintCellRenderer.getListCellRendererComponent(Ljavax / swing / JList; Ljava / lang / Object; IZZ)

输出:net.sourceforge.ganttproject.shape.PaintCellRenderer.getListCellRendererComponent(Ljavax / swing / JList; Ljava / lang / Object; int; boolean; boolean)

输入: net.sourceforge.ganttproject.ChartComponentBase $ 1.-init-(Lnet / sourceforge / ganttproject / ChartComponentBase;)

输出: net.sourceforge.ganttproject.ChartComponentBase $ 1.-init-(Lnet / sourceforge / ganttproject / ChartComponentBase;)

输入: net.sourceforge.ganttproject.GanttCalendar.-init-(III)

输出: net.sourceforge.ganttproject.GanttCalendar.-init-(int; int; int)

输入: net.sourceforge.ganttproject.GanttCalendar.-init-(Z)

输出: net.sourceforge.ganttproject.GanttCalendar.-init-(boolean)

我遇到的问题是,即使ChartComponentBase中的B最终也被替换了,并且最终出现了“ ChartComponentbytease”

仅当连续大写字母(I或B或Z或J或S)替换为半冒号时,该模式才有效 只能替换括号内的大写字母(I或B或Z或J或S)

我尝试解析字符串并将括号中的部分分开,并使用replaceAll然后重新组装字符串,但是它不起作用:

@IBAction func button_Tap(_ sender: UIButton) {
  self.buttons.forEach { $0.backgroundColor = $0 === sender ? .blue : .white  }
}

我觉得按照这些原则使用某些内容可能比使用replaceAll更合适:

                   methodname=methodname.substring(methodname.indexOf("("),methodname.indexOf(")")); 


                    methodname=methodname.replaceAll("B", "byte");
                    methodname=methodname.replaceAll("Z", "boolean");
                    methodname=methodname.replaceAll("I", "int");
                    methodname=methodname.replaceAll("J", "short");
                    methodname=methodname.replaceAll("S", "string");

2 个答案:

答案 0 :(得分:0)

正则表达式不是适合该工作的工具。

相反,编写如下代码:

String input = "net.sourceforge.ganttproject.shape.PaintCellRenderer.getListCellRendererComponent(Ljavax/swing/JList;Ljava/lang/Object;IZZ)\n" +
               "net.sourceforge.ganttproject.ChartComponentBase$1.-init-(Lnet/sourceforge/ganttproject/ChartComponentBase;)\n" +
               "net.sourceforge.ganttproject.GanttCalendar.-init-(III)\n" +
               "net.sourceforge.ganttproject.GanttCalendar.-init-([[Z)\n";

StringBuilder buf = new StringBuilder();
int start = 0;
for (int i = 0; (i = input.indexOf('(', i)) != -1; i++) {
    buf.append(input.substring(start, ++i));
    int arrays = 0;
    ARGLOOP: for (;;) {
        start = i;
        switch (input.charAt(i)) {
            case ')':
                break ARGLOOP;
            case '[':
                arrays++;   i++;
                continue ARGLOOP;
            case 'L':
                if ((i = input.indexOf(';', i)) == -1)
                    throw new IllegalArgumentException("Unended object type at index " + start);
                buf.append(input.substring(start + 1, i).replace('/', '.'));
                break;
            case 'Z': buf.append("boolean"); break;
            case 'B': buf.append("byte");    break;
            case 'C': buf.append("char");    break;
            case 'S': buf.append("short");   break;
            case 'I': buf.append("int");     break;
            case 'J': buf.append("long");    break;
            case 'F': buf.append("float");   break;
            case 'D': buf.append("double");  break;
            case 'V': buf.append("void");    break;
            default:
                throw new UnsupportedOperationException("Unknown type character at index " + i + ": " + input.charAt(i));
        }
        for (int j = 0; j < arrays; j++)
            buf.append("[]");
        buf.append(';');
        arrays = 0;
        i++;
    }
}
String output = buf.append(input.substring(start)).toString();
System.out.println(output);

输出

net.sourceforge.ganttproject.shape.PaintCellRenderer.getListCellRendererComponent(javax.swing.JList;java.lang.Object;int;boolean;boolean;)
net.sourceforge.ganttproject.ChartComponentBase$1.-init-(net.sourceforge.ganttproject.ChartComponentBase;)
net.sourceforge.ganttproject.GanttCalendar.-init-(int;int;int;)
net.sourceforge.ganttproject.GanttCalendar.-init-(boolean[][];)

答案 1 :(得分:0)

从我的答案中得到答案,用RegEx来实现这种递归问题是一项艰巨的任务。

为了给您一些提示和指导,我将其作为示例输入

net.sourceforge.ganttproject.shape.PaintCellRenderer.getListCellRendererComponent(Ljavax/swing/JList;Ljava/lang/Object;IZZ)

并应用了它:

\(([^;]*);([^;]*);(B?Z?I?J?S?]*)(B?Z?I?J?S?]*)(B?Z?I?J?S?]*)\)

您可以HERE对其进行检查

 Match 1
=========

Full match  81-123  `(Ljavax/swing/JList;Ljava/lang/Object;IZZ)` 
Group 1.    82-100  `Ljavax/swing/JList`<-----Group1 could be replaced as alias by $1
Group 2.    101-118 `Ljava/lang/Object`<-----Group2 could be replaced as alias by $2
Group 3.    119-120 `I`<-----Group3 could be replaced as alias by $3 
Group 4.    120-121 `Z`<-----Group4 could be replaced as alias by $4
Group 5.    121-122 `Z`<-----Group5 could be replaced as alias by $5

然后

swith(m.group(3))
{
                case 'I':
                    "($1;$2;int)";
                    break;
                case 'B':
                   "($1;$2;byte)";
                    break;
                  case 'Z':
                   "($1;$2;boolean)";
                    break;
                  case 'J':
                   "($1;$2;short)";
                    break;
                  case 'S':
                   "($1;$2;String)";
                    break;
                default:
                 break;
}

您必须重复此递归操作,并通过将第二个参数移至第三个参数,这样一个..... by m.group(4)和so.by m.group(5)... etc

在这里,我提出了一种方法,可以适应正则表达式可以真正解决的另一个问题。

public static String validate(String inputString) {
    String isDone = inputString;
    try {
      Pattern p = Pattern.compile("(([^;]*);([^;]*);(B?Z?I?J?S?]*)(B?Z?I?J?S?]*)(B?Z?I?J?S?]*))", Pattern.CASE_INSENSITIVE);
      Matcher m = p.matcher(isDone);

      while(m.find()) {
        System.out.println("Located at [" + m.group() + "] starting at " + m.start() + "and Ending at "
                           + (m.end() - 1));

      }
      isDone = isDone.replaceAll("(([^;]*);([^;]*);(B?Z?I?J?S?]*)(B?Z?I?J?S?]*)(B?Z?I?J?S?]*))", "($1;$2;XXXX,YYYY,ZZZZ,etc)");
    }
    catch(PatternSyntaxException pse) {

      System.err.println("Bad Regex " + pse.getMessage());
      System.err.println("Description :" + pse.getDescription());
      System.err.println("Index : " + pse.getIndex());
      System.err.println("Incorrect Pattern :" + pse.getPattern());
    }
    return isDone;
  }

其中XXXX,YYYY,ZZZZ等等价于byte,short,String,int,boolean..etc等可以替换您的别名$ 3,$ 4,$ 5,$ ...等