在这篇文章中,我们将学习如何使Java正则表达式不区分大小写Java编写的。 Java正则表达式用于从字符序列中查找、匹配和提取数据。 Java正则表达式默认区分大小写。但是借助正则表达式,我们可以使Java正则表达式不区分大小写。有两种方法可以使正则表达式不区分大小写:
- 使用 CASE_INSENSITIVE 标志
- 使用修饰符
1. 使用 CASE_INSENSITIVE 标志: Pattern 类的编译方法将 CASE_INSENSITIVE 标志与模式一起使用,使 Expression 不区分大小写。下面是实现:
Java
// Java program demonstrate How to make Java
// Regular Expression case insensitive in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG {
public static void main(String[] args)
{
// String
String str = "From GFG class. Welcome to gfg.";
// Create pattern to match along
// with the flag CASE_INSENSITIVE
Pattern patrn = Pattern.compile(
"gfg", Pattern.CASE_INSENSITIVE);
// All metched patrn from str case
// insensitive or case sensitive
Matcher match = patrn.matcher(str);
while (match.find()) {
// Print matched Patterns
System.out.println(match.group());
}
}
}
Java
// Java program demonstrate How to make Java
// Regular Expression case insensitive in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG {
public static void main(String[] args)
{
// String
String str = "From GFG class. Welcome to gfg.";
// Create pattern to match along
// with the ?i modifier
Pattern patrn = Pattern.compile("(?i)gfg");
// All metched patrn from str case
// insensitive or case sensitive
Matcher match = patrn.matcher(str);
while (match.find()) {
// Print matched Patterns
System.out.println(match.group());
}
}
}
输出
GFG
gfg
2. 使用修饰符: “ ?i”修饰符用于使Java正则表达式不区分大小写。因此,为了使Java正则表达式不区分大小写,我们将模式与“ ?i”修饰符一起传递,使其不区分大小写。下面是实现:
Java
// Java program demonstrate How to make Java
// Regular Expression case insensitive in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG {
public static void main(String[] args)
{
// String
String str = "From GFG class. Welcome to gfg.";
// Create pattern to match along
// with the ?i modifier
Pattern patrn = Pattern.compile("(?i)gfg");
// All metched patrn from str case
// insensitive or case sensitive
Matcher match = patrn.matcher(str);
while (match.find()) {
// Print matched Patterns
System.out.println(match.group());
}
}
}
输出
GFG
gfg