Java Pattern quote() Method
Example
Check if a text is exactly "1+1=2", without and with quote():
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String text = "1+1=2";
System.out.println(Pattern.matches("1+1=2", text));
System.out.println(Pattern.matches(Pattern.quote("1+1=2"), text));
}
}
Definition and Usage
The quote() method returns a regular expression that matches the given text exactly, character by character.
Some characters, like +, ., * and ?, have a special meaning in regular expressions. For example, + means "one or more of the character before", so the regular expression 1+1=2 does not match the text 1+1=2. After quote(), all characters are normal characters. This is useful when you search for text that comes from a user.
Tip: You can also use the Pattern.LITERAL flag in compile() to get the same result.
Syntax
public static String quote(String s)
Parameter Values
| Parameter | Description |
|---|---|
| s | Required. The text to match exactly. |
Technical Details
| Returns: | A regular expression, as a String, that matches the text exactly. |
|---|
Related Pages
❮ RegEx Methods