-1

I was given a Java exercise:
Break up camelCase writing into words, for example the input "camelCaseTest" should give the output "camel Case Test".

I found this solution online, but I don't understand all of it

public static String camelCaseBetter(String input) {
    input = input.replaceAll("([A-Z])", " $1");
    return input;
}

What does the $1 do? I think it just takes the String that is to be replaced (A-Z) and replaces it with itself (in this case the method also appends a space to break up the words)

I couldn't find a good explanation for $1, so I hope somebody here can explain it or share a link to the right resource which can explain it.

Ivar
  • 6,138
  • 12
  • 49
  • 61
  • `input "camelCaseTest" should give the output "camelCaseTest"` - this example seems to be broken as there's no difference between input and output. Do you mean output should be "camel Case Test"? – Thomas Nov 17 '21 at 09:25
  • `$1` is the first _group_, `(...)`, $2 the second etcetera. `$0` is all the match of the pattern. – Joop Eggen Nov 17 '21 at 09:26
  • @Thomas: I've edited the question to fix this (plus some minor typos) – Hans-Martin Mosner Nov 17 '21 at 09:58
  • 1
    @Mritunjay It’s similar and helpful, thanks. It’s about JavaScript, so I wouldn’t call it an exact duplicate. – Ole V.V. Nov 17 '21 at 10:05

1 Answers1

2

From the documentation of the String class:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll.

From Matcher.replaceAll

The replacement string may contain references to captured subsequences as in the appendReplacement method.

Then the appendReplacement method:

The replacement string may contain references to subsequences captured during the previous match: Each occurrence of ${name} or $g will be replaced by the result of evaluating the corresponding group(name) or group(g) respectively. For $g, the first number after the $ is always treated as part of the group reference. Subsequent numbers are incorporated into g if they would form a legal group reference. Only the numerals '0' through '9' are considered as potential components of the group reference. If the second group matched the string "foo", for example, then passing the replacement string "$2bar" would cause "foobar" to be appended to the string buffer. A dollar sign ($) may be included as a literal in the replacement string by preceding it with a backslash (\$).

So, $1 will reference the the first capturing group (whatever matches the pattern within the first parentheses of the regular expression).

([A-Z]) will match any uppercase character and place it in the first capturing group. $1 will then replace it with a space, followed by the matched uppercase character.

Ivar
  • 6,138
  • 12
  • 49
  • 61