0

An example of the string is 1-2.5.6/8/3.4?1=f-g&e=d&h=i and in JavaScript the code p = p.replace(new RegExp('\\b' + '\\w+' + '\\b', 'g'), k[c]) will replace the characters 1, 2, 5, 6, 8, 3, 4, 1, f, g, e, d, h, and i with their respective string that is returned from the k[c], a function which just takes the character from the string and returns another value from a dictionary. I am trying to implement the same thing in Java, but some of the replaced characters have characters like 1, 2, 5, 6, 8, etc. So delivery45-2.5.6/8/3.4?1=f-g&e=d&h=i will turn into STRINGelivery45-2.5.6/8/3.4?1=f-g&e=d&h=i. Is there a to implement the same thing in Java as it does in JavaScript?

Here is what I am currently using in Java:

Pattern pattern = Pattern.compile("\\b\\w+\\b");
Matcher matcher = pattern.matcher(p);
while (matcher.find()) {
    String matchedString = matcher.group();
    String replacementString = z.apply(String.valueOf(matchedString));
    p = p.replace(matchedString, replacementString);
}

p being the original string, and z acting like k[c].

The result ends up being something like STRING_tliv56287592ry45-2.5.6/8/3.4?1=f-g&e=d&h=i which goes until it can't replace anymore.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
test test
  • 1
  • 3
  • Does this answer your question? [Java; String replace (using regular expressions)?](https://stackoverflow.com/questions/632204/java-string-replace-using-regular-expressions) – m0skit0 Dec 07 '22 at 23:20

1 Answers1

0

I have found the solution. I created 1 ArrayLists with:

ArrayList<Integer> listint = new ArrayList<>();

Then with the regex matcher I got the index value of the matches and added them to the list

Pattern pattern = Pattern.compile("\\b\\w+\\b");
Matcher matcher = pattern.matcher(p);
while (matcher.find()) {
                listint.add(matcher.start());
}

Then I used a for loop to go over the Arraylist to replace the original string from right to left because if you did it from left to right it would shift the index values which would ruin the string.

for (int i = listint.size() - 1; i >= 0; i--) {
                String startz = p.substring(0, listint.get(i));
                String middle = liststr.get(i);
                String endz = p.substring(listint.get(i) + 1);
                p = startz + middle + endz;
            }
test test
  • 1
  • 3
  • This is not a good (efficient) solution. You can do the replacement using a `Matcher` and a `StringBuffer` (in more recent version, also `StringBuilder`). See the documentation of [`Matcher.appendReplacement`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Matcher.html#appendReplacement(java.lang.StringBuilder,java.lang.String)) – Mark Rotteveel Dec 08 '22 at 17:10