Java regex: how to replace the whole character inside a parenthesis?

How do I replace:

((90+1)%(100-4)) + ((90+1)%(100-4/(6-4))) - (var1%(var2%var3(var4-var5))) 

from

 XYZ((90+1),(100-4)) + XYZ((90+1),100-4/(6-4)) - XYZ(var1,XYZ(var2,var3(var4-var5))) 

with regex?

Thanks J

0
source share
4 answers

This does not seem to work very well for regular expression. It looks like you could write a quick recursive descent parser. If I understand you correctly, do you want to replace the infix% operator with the name of the XYZ function?

So (expression expression%) becomes XYZ (expression, expression)

It looks like a good resource to learn: http://www.cs.uky.edu/~lewis/essays/compilers/rec-des.html

+1
source

I donโ€™t know much about regex, but try looking at this, especially 9 and 10: http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/

And of course, http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html

You could at least check them until a detailed answer appears.

0
source

See this code:

  String input = "((90+1)%(100-4)) + ((90+1)%(100-4/(6-4))) - (var1%(var2%var3(var4-var5)))"; input = input.replaceAll("%", ","); int level = 0; List<Integer> targetStack = new ArrayList<Integer>(); List<Integer> splitIndices = new ArrayList<Integer>(); // add the index of last character as default checkpoint splitIndices.add(input.length()); for (int i = input.length() - 1; i >= 0; i--) { if (input.charAt(i) == ',') { targetStack.add(level - 1); } else if (input.charAt(i) == ')') { level++; } else if (input.charAt(i) == '(') { level--; if (!targetStack.isEmpty() && level == targetStack.get(targetStack.size() - 1)) { splitIndices.add(i); } } } Collections.reverse(splitIndices); // reversing the indices so that they are in increasing order StringBuilder result = new StringBuilder(); for (int i = 1; i < splitIndices.size(); i++) { result.append("XYZ"); result.append(input.substring(splitIndices.get(i - 1), splitIndices.get(i))); } System.out.println(result); 

The output is done as you expect:

 XYZ((90+1),(100-4)) + XYZ((90+1),(100-4/(6-4))) - XYZ(var1,XYZ(var2,var3(var4-var5))) 

However, keep in mind that it is a bit hacked and may not work as you expect. By the way, I had to change the result a bit: I added a couple of brackets: XYZ ((90 + 1), ( 100-4 / (6-4 ) )) because otherwise you will not follow your own conventions. Hope this code helps you. For me it was a good exercise, at least.

0
source

Will it meet your requirements to do the following:

  • Find ( in the first position or before the space and replace it with XYZ(
  • Find % and replace it with ,

If these two instructions are sufficient and satisfactory, you can convert the original string into three "moves":

  • Replace ^\( with XYZ(
  • Replace \( with XYZ(
  • Replace % with ,
0
source

Source: https://habr.com/ru/post/1401761/


All Articles