1
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("where test = (:viztest)");
      System.out.print("Return Value :" );
      System.out.println(Str.replaceFirst("(:viztest)", "any('25','324')"));
   }
}

The result to this is

$javac Test.java
$java -Xmx128M -Xms16M Test
Return Value :where test = (any('25','324'))

Where it should be where test = any('25','324')

Why does it ignore replacing the parenthesis and how it should be fixed?

1
  • 1
    Your first step should always be the documentation, which quite clearly says "Replaces the first substring of this string that matches the given regular expression with the given replacement." So then you'd ask yourself if the paren issue might relate to that "regular expression" thing, and look at those... Commented Nov 28, 2017 at 8:08

3 Answers 3

11

You need escape the parenthesis (the argument is a regex, (...) defines a capture group):

Str.replaceFirst("\\(:viztest\\)")

or

Str.replaceFirst(Pattern.quote("(:viztest)")
Sign up to request clarification or add additional context in comments.

3 Comments

with \\( as it is a regex escape
Thank you i tried before with \ slash but didn't work
Pattern.quote("(:viztest)") is the most reliable way to ensure everything that needs to be escaped is escaped, whilst leaving your original strings intact.
1

This is easy: replaceFirst expects a regular expression as first parameter. In a regular expression, parentheses indicate a group. You need to escape them with backslashes.

https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#replaceFirst-java.lang.String-java.lang.String-

Comments

0

You can enclose the brackets in [] and it will remove those also:

System.out.println(Str.replaceFirst("[(]:viztest[)]", "any('25','324')"));

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.