1   /*
2    * %W% %E%
3    *
4    * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
5    * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6    */
7   
8   package java.util.regex;
9   
10  import sun.security.action.GetPropertyAction;
11  
12  
13  /**
14   * Unchecked exception thrown to indicate a syntax error in a
15   * regular-expression pattern.
16   *
17   * @author  unascribed
18   * @version %I%, %E%
19   * @since 1.4
20   * @spec JSR-51
21   */
22  
23  public class PatternSyntaxException
24      extends IllegalArgumentException
25  {
26  
27      private final String desc;
28      private final String pattern;
29      private final int index;
30  
31      /**
32       * Constructs a new instance of this class.
33       *
34       * @param  desc
35       *         A description of the error
36       *
37       * @param  regex
38       *         The erroneous pattern
39       *
40       * @param  index
41       *         The approximate index in the pattern of the error,
42       *         or <tt>-1</tt> if the index is not known
43       */
44      public PatternSyntaxException(String desc, String regex, int index) {
45      this.desc = desc;
46      this.pattern = regex;
47      this.index = index;
48      }
49  
50      /**
51       * Retrieves the error index.
52       *
53       * @return  The approximate index in the pattern of the error,
54       *         or <tt>-1</tt> if the index is not known
55       */
56      public int getIndex() {
57      return index;
58      }
59  
60      /**
61       * Retrieves the description of the error.
62       *
63       * @return  The description of the error
64       */
65      public String getDescription() {
66      return desc;
67      }
68  
69      /**
70       * Retrieves the erroneous regular-expression pattern.
71       *
72       * @return  The erroneous pattern
73       */
74      public String getPattern() {
75      return pattern;
76      }
77  
78      private static final String nl =
79      java.security.AccessController
80          .doPrivileged(new GetPropertyAction("line.separator"));
81  
82      /**
83       * Returns a multi-line string containing the description of the syntax
84       * error and its index, the erroneous regular-expression pattern, and a
85       * visual indication of the error index within the pattern.
86       *
87       * @return  The full detail message
88       */
89      public String getMessage() {
90          StringBuffer sb = new StringBuffer();
91          sb.append(desc);
92      if (index >= 0) {
93          sb.append(" near index ");
94          sb.append(index);
95      }
96          sb.append(nl);
97          sb.append(pattern);
98      if (index >= 0) {
99          sb.append(nl);
100         for (int i = 0; i < index; i++) sb.append(' ');
101         sb.append('^');
102     }
103         return sb.toString();
104     }
105 
106 }
107