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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.