- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to match the regex meta characters in java as literal characters.
The compile method of the patter class accepts two parameters −
- A string value representing the regular expression.
- An integer value a field of the Pattern class.
The filed LITERAL of the enables literal parsing of the pattern. i.e. all the regular expression metacharacters and escape sequences don’t have any special meaning they are treated as literal characters. Therefore, If you need to match the regular expression metacharacters as normal characters you need to pass this as a flag value to the compile() method along with the regular expression.
Example
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String[] args) { System.out.println("Enter input data: "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "^[0-9]"; //Creating a Pattern object Pattern pattern = Pattern.compile(regex, Pattern.LITERAL); //Creating a Matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; System.out.println(matcher.group()); } System.out.println("Number of matches: "+count); } }
Output 1
Enter input data: 9848022338 Number of matches: 0
Output 2
Enter input data: ^[0-9] ^[0-9] Number of matches: 1
- Related Articles
- How to match word characters using Java RegEx?
- How to match a range of characters using Java regex
- How to match a fixed set of characters using Java RegEx
- Matching Nonprintable Characters using Java regex
- JavaScript regex - How to replace special characters?
- How to escape all special characters for regex in Python?
- How to get last 2 characters from string in C# using Regex?
- How to match any character using Java RegEx
- How to match word boundaries using Java RegEx?
- How to match end of the input using Java RegEx?
- How to match the beginning of the input using Java RegEx?
- How to match digits using Java Regular Expression (RegEx)
- How to match non-word boundaries using Java RegEx?
- Java regex program to match parenthesis "(" or, ")".
- How to replace characters on String in Java?

Advertisements