1

I need to convert the characters followed by a - in a string to uppercase.

Using Regex101, the following works like a charm:

Regex -> (\-[a-z]|\_[a-z])
Substitution -> \U$1

Regex101

But I don't know how to properly translate this to a Java RegEx. Here's what I got so far:

StringBuilder str = new StringBuilder("this-is-a_test");
Pattern p = Pattern.compile("(\\-[a-z]|\\_[a-z])");
p.matcher(str).replaceAll("\\p{Lu}$1");

System.out.println(str);

What exactly am I doing wrong?

Daniel Bertoldi
  • 359
  • 4
  • 14
  • 2
    You might shorten your pattern to `([-_])([a-z])` https://regex101.com/r/gu83Cr/1 and I think you can see this answer to convert the second capturing group to uppercase https://stackoverflow.com/questions/43467120/java-replace-characters-with-uppercase-around-before-and-after-specific-charac – The fourth bird Jan 23 '20 at 20:10

1 Answers1

3
  1. public String replaceAll​(String replacement) doesn't modify source text used by Matcher, but it returns new (separate) String with replaced content based on original text passed to matcher. So p.matcher(str).replaceAll("\\p{Lu}$1"); will not modify str but will return new String which you are ignoring.

  2. Also .replaceAll("\\p{Lu}$1") doesn't treat \\p{Lu} as indicator of uppercase change like \U does in JavaScript. Java's regular expression engine is different beast and \\p{Lu} in replacement is treated as simple string without special meaning, so your code would result in thisp{Lu}-isp{Lu}-ap{Lu}_test.

If you want to easily generate dynamic replacement based on current match you can use public String replaceAll​(Function<MatchResult,​String> replacer) added in Java 9. This way you can provide implementation of Function<MatchResult,​String> functional interface with lambda like match -> /*code using match and returning proper replacement*/

In your case it can look like:

StringBuilder str = new StringBuilder("this-is-a_test");
Pattern p = Pattern.compile("[-_][a-z]");
String replaced = p.matcher(str).replaceAll(match -> match.group(0).toUpperCase());
System.out.println(replaced);

which results in this-Is-A_Test.

BTW I simplified your regex to [-_][a-z] since IMO it is easier to understand.

Pshemo
  • 122,468
  • 25
  • 185
  • 269