Java tutorial
//package com.java2s; import java.util.regex.*; public class Main { /** * Pattern.pattern and Pattern.toString ignore any flags supplied to * Pattern.compile, so the regular expression you get out doesn't * correspond to what the Pattern was actually matching. This fixes that. * * Note that there are some flags that can't be represented. * * FIXME: why don't we use Pattern.LITERAL instead of home-grown escaping * code? Is it because you can't do the reverse transformation? Should we * integrate that code with this? */ public static String toString(Pattern pattern) { String regex = pattern.pattern(); final int flags = pattern.flags(); if (flags != 0) { StringBuilder builder = new StringBuilder("(?"); toStringHelper(builder, flags, Pattern.UNIX_LINES, 'd'); toStringHelper(builder, flags, Pattern.CASE_INSENSITIVE, 'i'); toStringHelper(builder, flags, Pattern.COMMENTS, 'x'); toStringHelper(builder, flags, Pattern.MULTILINE, 'm'); toStringHelper(builder, flags, Pattern.DOTALL, 's'); toStringHelper(builder, flags, Pattern.UNICODE_CASE, 'u'); builder.append(")"); regex = builder.toString() + regex; } return regex; } private static void toStringHelper(StringBuilder result, int flags, int flag, char c) { if ((flags & flag) != 0) { result.append(c); } } }