0

How can I use java string replaceAll or replaceFirst to append to beginning?

String joe = "Joe";
String helloJoe = joe.replaceAll("\\^", "Hello");

Desired Output: "Hello Joe"

3
  • 4
    Why are you using regex for this? Commented Mar 15, 2015 at 2:11
  • You can't "append to the beginning of a string" anyway since strings in Java are immutable. You'll create a new string object anyway. Commented Mar 15, 2015 at 2:15
  • Okey dokey! lambdaStuff.map(s->s.replace("^","Hello")).orElse("")); Commented Mar 15, 2015 at 5:19

2 Answers 2

5

You don't need to escape ^ because ^ is a special meta character in regex which matches the start of a line.

String helloJoe = whatever.replaceFirst("^", "Hello ");
Sign up to request clarification or add additional context in comments.

Comments

2

You could perform a simple String append with +, or String.format(String, Object...) like

String whatever = "Joe";
String helloJoe = String.format("Hello %s", whatever);
// String helloJoe = "Hello " + whatever;
System.out.println(helloJoe);

Output is (as requested)

Hello Joe

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.