1

In JavaScript it's possible to use lambda functions with the replace function, in Java string.replaceAll will not allow this. How can I do the same thing in as below in Java?:

replaceDotHandlesWithUnderscore(input) {
  // e.g. {my.nested.value} to {my_nested_value}
  // e.g. {my.nested.value, select, true {Yes} false {No}} to {my_nested_value, select, true {Yes} no {false}}
  return input.replace(
    /\{(\s*)(\w+(\.\w+)*)/g,
    (matches, space, handle) => `{${space}${handle.replace(/\./g, '_')}`
  );
}

It's fine to go with Java 1.8 or 1.9 solutions to this.

tirithen
  • 3,219
  • 11
  • 41
  • 65
  • why would `String.replaceAll` not do this? – Naman Nov 03 '17 at 11:03
  • 1
    @nullpointer there is no way to use a callback inside `replaceAll`, but there is [`Matcher.appendReplacement()`](https://stackoverflow.com/a/377484/3832970) (also, [example here](https://stackoverflow.com/a/19737857/3832970)). – Wiktor Stribiżew Nov 03 '17 at 11:04
  • @WiktorStribiżew Looking at the *eg* in the code looked simple to me, maybe I don' understand the code in javascript there. – Naman Nov 03 '17 at 11:05
  • 1
    @nullpointer That is ES6 syntax. `matches` is the match value, `space` is capturing group 1, `handle` is Group 2 value. They are used in an [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – Wiktor Stribiżew Nov 03 '17 at 11:05
  • Thanks @WiktorStribiżew with that example and https://examples.javacodegeeks.com/core-java/util/regex/matcher-appendreplacement-example-part-2/ I think I can find my way now :) – tirithen Nov 03 '17 at 11:08

0 Answers0