Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent the double quotes character (") in regex? [duplicate]

Tags:

java

regex

char

I need to use regex, to check if a string starts with a double quotes character (") and ends with a double quotes character too.

The problem is I can't use a double quotes character, cause it gets confused. Is there any other way to represent a double quotes character " in regex, or in string in general?

String s = """;    // ?
like image 627
Gigalala Avatar asked May 26 '13 17:05

Gigalala


People also ask

How do you put quotes in regex?

Try putting a backslash ( \ ) followed by " .

Do I need to escape quotes in regex?

In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped. Some flavors only use ^ and $ as metacharacters when they are at the start or end of the regex respectively. In those flavors, no additional escaping is necessary. It's usually just best to escape them anyway.


1 Answers

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

like image 70
stinepike Avatar answered Oct 13 '22 08:10

stinepike