实现说明
COMMENTS 模式排版正则可以归结为类 ReadableRegex和函数 main。
这个文件只在 for (String input : new String[] {"[email protected]", "[email protected]"}) 里循环。
使用要点
- 直接运行文件,输出会带上标签,比如
a b ->、ab ->——输出的每一行都能指回产生它的那次调用。
常见问题
运行「COMMENTS 模式排版正则」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 a b ->、ab -> 这类标签。
核心语句
(\\.[\\w-]+)+ # dot-separated suffix chain
$ # end
""", Pattern.COMMENTS);
Pattern spaced = Pattern.compile("a[ ]b");
代码示例
import java.util.regex.Pattern;
public class ReadableRegex {
public static void main(String[] args) {
// Pattern.COMMENTS(内联写法 (?x)):空白与 # 注释被忽略,正则可排版成可读形式
Pattern email = Pattern.compile("""
^[\\w.+-]+ # local part
@ # at sign
[\\w-]+ # domain label
(\\.[\\w-]+)+ # dot-separated suffix chain
$ # end
""", Pattern.COMMENTS);
for (String input : new String[] {"[email protected]", "[email protected]"}) {
System.out.println(input + " -> " + email.matcher(input).matches());
}
// 字面空白要写成 [ ](或 \\Q...\\E、\\ 转义),否则会被当作排版忽略
Pattern spaced = Pattern.compile("a[ ]b");
System.out.println("a b -> " + spaced.matcher("a b").matches());
System.out.println("ab -> " + spaced.matcher("ab").matches());
}
}