在Java中,要实现正则表达式的大小写不敏感匹配,你可以使用Pattern.CASE_INSENSITIVE标志或者(?i)模式修饰符。以下是两种方法的示例:
方法1:使用Pattern.CASE_INSENSITIVE标志
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CaseInsensitiveRegex {
public static void main(String[] args) {
String input = "Hello World";
String regex = "hello world";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("匹配成功");
} else {
System.out.println("匹配失败");
}
}
}
方法2:使用(?i)模式修饰符
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CaseInsensitiveRegex {
public static void main(String[] args) {
String input = "Hello World";
String regex = "(?i)hello world";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("匹配成功");
} else {
System.out.println("匹配失败");
}
}
}
这两种方法都可以实现大小写不敏感的匹配。在这个例子中,输入字符串"Hello World"与正则表达式"hello world"(或"(?i)hello world")匹配成功。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。