我遇到了用 Java 代码编写的以下情况:
String pattern = "(?i:U[A-Z0-9]C.*)";
if (foo.matches(pattern))) {
...
我不明白 ?i:
是什么意思。我见过 (?i)
用于指示不区分大小写,但不确定此处的形式。
感谢您的帮助!
最佳答案
在 Pattern
的 javadoc 中,它被定义为:
(?idmsuxU-idmsuxU)
- Nothing, but turns match flags i d m s u x U on - off
(?idmsux-idmsux:X)
- X, as a non-capturing group with the given flags i d m s u x on - off
鉴于 (?i)
将标志变为 CASE_INSENSITIVE
对于正则表达式模式的其余部分,(?i:X)
只为 X
打开标志。
例如这些是相同的1:
Foo(?i)Bar(?-i)Baz
Foo(?i:Bar)Baz
另请注意 javadoc 中的以下注释:
In Perl, embedded flags at the top level of an expression affect the whole expression. In this class, embedded flags always take effect at the point at which they appear, whether they are at the top level or within a group; in the latter case, flags are restored at the end of the group just as in Perl.
1) 这并不意味着 (?i)X(?-i)
和 (?i:X)
总是相同的,看评论。
更新 - 证明:
System.out.println("Foo(?i)Bar(?-i)Baz Foo(?i:Bar)Baz");
for (String s : new String[] {"FooBarBaz","FoobarBaz","FooBARBaz","FoobARBaz","FOOBarBaz","FooBarBAZ"})
System.out.printf(" %-18s%-12s%s%n", s.matches("Foo(?i)Bar(?-i)Baz"), s.matches("Foo(?i:Bar)Baz"), s);
输出
Foo(?i)Bar(?-i)Baz Foo(?i:Bar)Baz
true true FooBarBaz
true true FoobarBaz
true true FooBARBaz
true true FoobARBaz
false false FOOBarBaz
false false FooBarBAZ
关于Java 正则表达式 - 什么是?i : mean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55048296/