How to Make Java Regular Expression Case Insensitive in Java?In Java, regular expressions (regex) are powerful tools for pattern matching within strings. By default, Java's regex engine is case sensitive, meaning it distinguishes between uppercase and lowercase letters in patterns and input strings. However, there are methods and techniques to make Java regular expressions case insensitive when needed.
1. Using CASE_INSENSITIVE flagJava provides a straightforward way to make regular expressions case insensitive by using the Pattern.CASE_INSENSITIVE flag with the compile method of the Pattern class. This flag allows the regex engine to ignore differences in letter case when matching patterns against input strings. File Name: RegexExample.java Output: Match found! Case Insensitivity with Complex PatternFile Name: RegexExample2.java Output: Match found at index: 0 Match found at index: 12 Match found at index: 29 Case Insensitivity with GroupsTo use case insensitivity with regular expression groups in Java, we apply the same CASE_INSENSITIVE flag but include groups in pattern. Here's an example: File Name: CaseInsensitiveGroupsExample.java Output: Full match: name: John (email: [email protected]) Name group: name: John Name: John Email group: [email protected] Full match: name: alice (email: [email protected]) Name group: name: alice Name: alice Email group: [email protected] 2. Using ModifierAlternatively, we can embed the (?i) modifier directly within the regex pattern itself. It applies case insensitivity locally to the part of the pattern where it is used. File Name: UsingModifier.java Output: Match found! Next TopicImage-processing-in-java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India