0

How to replace a ? from string with another. Here is my sample code

String oldString = "I am ? ?";
String newString = oldString.replaceAll("?|?", "Java|Developer");
System.out.println(newString);

and gives error

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0

If I use another way like

String oldString = "I am J D";
String newString = oldString.replaceAll("J|D", "Java|Developer");
System.out.println(newString);

and the output is

I am Java|Developer Java|Developer

My requirement is

Input: I am ? ?
Output: I am Java Developer

Is there any way to achieve it?

6
  • Read a regular expression tutrial, e.g. docs.oracle.com/javase/tutorial/essential/regex Commented May 25, 2022 at 7:01
  • 1
    Well, one not-too-elegant way would be oldString.replace("?", "%s").formatted("Java", "Developer"). Commented May 25, 2022 at 7:03
  • @MCEmperor the way is working for characters not the "?". Is there any way to use "?". Commented May 25, 2022 at 7:07
  • I have found the solution for "?" to "\\?" from stackoverflow.com/a/23864310/16974685 Commented May 25, 2022 at 7:11
  • @AlyanAhmed Read carefully. I used replace instead of replaceAll. Commented May 25, 2022 at 7:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.