我找到了this question关于如何移植 PHP 的 preg_match
到Java(建议使用 String.matches()
。但是,我仍然遇到以下情况的问题:
PHP:
preg_match('/<(h1|h2|h3|h4|ul|td|div|table)/i', '<h1>')
=>返回1
Java:
"<h1>".matches("/<(h1|h2|h3|h4|ul|td|div|table)/i")
=>返回false
为什么会这样?
最佳答案
在 Java 中,matches()
需要完整的字符串匹配。并且您不需要正则表达式分隔符。
"<h1>".matches("(?i)<(h1|h2|h3|h4|ul|td|div|table)>")
如果您打算在 Java 中使用相同的正则表达式,请将 Matcher
与 find()
一起使用(find
将匹配输入字符串中的任何位置)和 Pattern.CASE_INSENSITIVE
将充当 PHP 中的 i
选项):
String str = "<h1>";
String rx = "<(h1|h2|h3|h4|ul|td|div|table)";
Pattern ptrn = Pattern.compile(rx, Pattern.CASE_INSENSITIVE);
Matcher m = ptrn.matcher(str);
while (m.find()) {
System.out.println(m.group(0));
}
关于java - 使用 String.matches 将 PHP preg_match 逻辑移植到 Java 时不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31377786/