aDoN
aDoN

Reputation: 1951

Insert character before specific character Java

I have been taking a look at the regular expressions and how to use it in Java for the problem I have to solve. I have to insert a \ before every ". This is what I have:

public class TestExpressions {
    public static void main (String args[]) {

        String test = "$('a:contains(\"CRUCERO\")')";
        test = test.replaceAll("(\")","$1%");
        System.out.println(test);
    }
}

The ouput is:

$('a:contains("%CRUCERO"%)')

What I want is:

$('a:contains(\"CRUCERO\")')

I have changed % for \\ but have an error StringIndexOutofBounds don't know why. If someone can help me I would appreciate it, thank you in advance.

Upvotes: 1

Views: 5613

Answers (4)

aliteralmind
aliteralmind

Reputation: 20163

If your goal is escape text for Java strings, then instead of regular expressions, consider using

String escaped = org.apache.commons.lang.StringEscapeUtils.
   escapeJava("$('a:contains(\"CRUCERO\")')");
System.out.println(escaped);

Output:

$('a:contains(\"CRUCERO\")')

JavaDoc: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#escapeJava(java.lang.String)

Upvotes: 1

Pshemo
Pshemo

Reputation: 124215

I have to insert a \ before every "

You can try with replace which automatically escapes all regex metacharacters and doesn't use any special characters in replacement part so you can simply use String literals you want to be put in matched part.

So lets just replace " with \" literal. You can write it as

test = test.replace("\"", "\\\"");

Upvotes: 1

Pedro Lobito
Pedro Lobito

Reputation: 98881

String result = subject.replaceAll("(?i)\"CRUCERO\"", "\\\"CRUCERO\\\"");

EXPLANATION:

Match the character string “"CRUCERO"” literally (case insensitive) «"CRUCERO"»
Ignore unescaped backslash «\»
Insert the character string “"CRUCERO” literally «"CRUCERO»
Ignore unescaped backslash «\»
Insert the character “"” literally «"»

Upvotes: 1

anubhava
anubhava

Reputation: 784998

If you want to insert backspace before quote then use:

test = test.replaceAll("(\")","\\\\$1"); // $('a:contains(\"CRUCERO\")')

Or if you want to avoid already escaped quote then use negative lookbehind:

String test = "$('a:contains(\\\"CRUCERO\")')";
test = test.replaceAll("((?<!\\\\)\")","\\\\$1"); // $('a:contains(\"CRUCERO\")')

Upvotes: 1

Related Questions