- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Regular Expression Q Metacharacter in Java
The subexpression/metacharacter "\Q" escapes all characters up to "\E" i.e. you can escape metacharacters in the regular expressions by placing them in between \Q and \E. For example, the expression [aeiou] matches the strings with vowel letters in it.
Example
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SampleProgram { public static void main( String args[] ) { String regex = "[aeiou]"; Scanner sc = new Scanner(System.in); System.out.println("Enter input string: "); String input = sc.nextLine(); //Creating a Pattern object Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); if(matcher.find()) { System.out.println("Match occurred"); } else { System.out.println("Match not occurred"); } } }
Output
Enter input string: sample Match occurred
But, if you use the same expression with in \Q and \E as \Q[aeiou]\E It matches the same sequence of characters "[aeiou]" in the given string. In short the meta characters loses their meaning and will be treated as normal characters
Example
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SampleProgram { public static void main( String args[] ) { String regex = "\Q[aeiou]\E"; Scanner sc = new Scanner(System.in); System.out.println("Enter input string: "); String input = sc.nextLine(); //Creating a Pattern object Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); if(matcher.find()) { System.out.println("Match occurred"); } else { System.out.println("Match not occurred"); } } }
Output 1
Enter input string: sample Match not occurred
Output 2
Enter input string: The letters [aeiou] are vowels in English alphabet Match occurred
Advertisements