Java 正则表达式 - 什么是?i : mean?

标签 java regex

我遇到了用 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/

相关文章:

用于集成 WSDL、REST 等的 Java 框架

mysql - 如何在where子句中写mysql正则表达式?

php - 查找字符串中重叠的所有子字符串

c# - C# 的简单正则表达式帮助

替换字符串中的字符代码 8217 时出现 PHP 意外输出

java - 为什么这个返回 lambda 的方法取决于接口(interface)方法的返回类型?

java - 序列化和对象有意义吗

java - 查询的步骤是什么?什么是先看web.xml还是context.xml?

java - 为什么 HttpURLConnection 不发送数据,除非我尝试接收一些东西

正则表达式匹配行尾