It’s also possible to enable various flags using embedded flag expressions. Embedded flag expressions are an alternative to the two-argument version of compile, and are specified in the regular expression itself. The example below is use (?i)
flag expression to enable case-insensitive matching.
Another flag expressions are listed below:
(?x)
, equivalent withPattern.COMMENTS
(?m)
, equivalent withPattern.MULTILINE
(?s)
, equivalent withPattern.DOTTAL
(?u)
, equivalent withPattern.UNICODE_CASE
(?d)
, equivalent withPattern.UNIX_LINES
package org.kodejava.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmbeddedFlagDemo {
public static void main(String[] args) {
// Define regex which starting with (?i) to enable
// case-insensitive matching
String regex = "(?i)the";
String text = "The quick brown fox jumps over the lazy dog";
// Obtain the required matcher
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
// Find every match and print it
while (matcher.find()) {
System.out.format("Text \"%s\" found at %d to %d.%n",
matcher.group(), matcher.start(),
matcher.end());
}
}
}
The result of the program is:
Text "The" found at 0 to 3.
Text "the" found at 31 to 34.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024