RegularExpressionEngine.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */



  20. package org.openspcoop2.utils.regexp;

  21. import java.util.ArrayList;
  22. import java.util.Arrays;
  23. import java.util.List;
  24. import java.util.regex.Matcher;
  25. import java.util.regex.Pattern;

  26. /**
  27.  * Engine
  28.  *
  29.  * @author Andrea Poli (apoli@link.it)
  30.  * @author $Author$
  31.  * @version $Rev$, $Date$
  32.  */

  33. public class RegularExpressionEngine {
  34.    
  35.     private RegularExpressionEngine() {}

  36.     /**
  37.      * NOTA: Le regole sotto riportate sono state prese da http://download-llnw.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html
  38.      *       Riferirsi quindi alle API della versione di java corretta, per eventuali aggiornamenti.
  39.      * */
  40.    
  41.     /**
  42.     * Summary of regular-expression constructs
  43.      
  44.     Characters
  45.     x   The character x
  46.     \\  The backslash character
  47.     \0n     The character with octal value 0n (0 <= n <= 7)
  48.     \0nn    The character with octal value 0nn (0 <= n <= 7)
  49.     \0mnn   The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)
  50.     \xhh    The character with hexadecimal value 0xhh
  51.     \\uhhhh     The character with hexadecimal value 0xhhhh
  52.     \t  The tab character ('\u0009')
  53.     \n  The newline (line feed) character ('\u000A')
  54.     \r  The carriage-return character ('\u000D')
  55.     \f  The form-feed character ('\u000C')
  56.     \a  The alert (bell) character ('\u0007')
  57.     \e  The escape character ('\u001B')
  58.     \cx     The control character corresponding to x
  59.      
  60.     Character classes
  61.     [abc]   a, b, or c (simple class)
  62.     [^abc]  Any character except a, b, or c (negation)
  63.     [a-zA-Z]    a through z or A through Z, inclusive (range)
  64.     [a-d[m-p]]  a through d, or m through p: [a-dm-p] (union)
  65.     [a-z&&[def]]    d, e, or f (intersection)
  66.     [a-z&&[^bc]]    a through z, except for b and c: [ad-z] (subtraction)
  67.     [a-z&&[^m-p]]   a through z, and not m through p: [a-lq-z](subtraction)
  68.      
  69.     Predefined character classes
  70.     .   Any character (may or may not match line terminators)
  71.     \d  A digit: [0-9]
  72.     \D  A non-digit: [^0-9]
  73.     \s  A whitespace character: [ \t\n\x0B\f\r]
  74.     \S  A non-whitespace character: [^\s]
  75.     \w  A word character: [a-zA-Z_0-9]
  76.     \W  A non-word character: [^\w]
  77.      
  78.     POSIX character classes (US-ASCII only)
  79.     \p{Lower}   A lower-case alphabetic character: [a-z]
  80.     \p{Upper}   An upper-case alphabetic character:[A-Z]
  81.     \p{ASCII}   All ASCII:[\x00-\x7F]
  82.     \p{Alpha}   An alphabetic character:[\p{Lower}\p{Upper}]
  83.     \p{Digit}   A decimal digit: [0-9]
  84.     \p{Alnum}   An alphanumeric character:[\p{Alpha}\p{Digit}]
  85.     \p{Punct}   Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
  86.     \p{Graph}   A visible character: [\p{Alnum}\p{Punct}]
  87.     \p{Print}   A printable character: [\p{Graph}\x20]
  88.     \p{Blank}   A space or a tab: [ \t]
  89.     \p{Cntrl}   A control character: [\x00-\x1F\x7F]
  90.     \p{XDigit}  A hexadecimal digit: [0-9a-fA-F]
  91.     \p{Space}   A whitespace character: [ \t\n\x0B\f\r]
  92.      
  93.     java.lang.Character classes (simple java character type)
  94.     \p{javaLowerCase}   Equivalent to java.lang.Character.isLowerCase()
  95.     \p{javaUpperCase}   Equivalent to java.lang.Character.isUpperCase()
  96.     \p{javaWhitespace}  Equivalent to java.lang.Character.isWhitespace()
  97.     \p{javaMirrored}    Equivalent to java.lang.Character.isMirrored()
  98.      
  99.     Classes for Unicode blocks and categories
  100.     \p{InGreek}     A character in the Greek block (simple block)
  101.     \p{Lu}  An uppercase letter (simple category)
  102.     \p{Sc}  A currency symbol
  103.     \P{InGreek}     Any character except one in the Greek block (negation)
  104.     [\p{L}&&[^\p{Lu}]]      Any letter except an uppercase letter (subtraction)
  105.      
  106.     Boundary matchers
  107.     ^   The beginning of a line
  108.     $   The end of a line
  109.     \b  A word boundary
  110.     \B  A non-word boundary
  111.     \A  The beginning of the input
  112.     \G  The end of the previous match
  113.     \Z  The end of the input but for the final terminator, if any
  114.     \z  The end of the input
  115.      
  116.     Greedy quantifiers
  117.     X?  X, once or not at all
  118.     X*  X, zero or more times
  119.     X+  X, one or more times
  120.     X{n}    X, exactly n times
  121.     X{n,}   X, at least n times
  122.     X{n,m}  X, at least n but not more than m times
  123.      
  124.     Reluctant quantifiers
  125.     X??     X, once or not at all
  126.     X*?     X, zero or more times
  127.     X+?     X, one or more times
  128.     X{n}?   X, exactly n times
  129.     X{n,}?  X, at least n times
  130.     X{n,m}?     X, at least n but not more than m times
  131.      
  132.     Possessive quantifiers
  133.     X?+     X, once or not at all
  134.     X*+     X, zero or more times
  135.     X++     X, one or more times
  136.     X{n}+   X, exactly n times
  137.     X{n,}+  X, at least n times
  138.     X{n,m}+     X, at least n but not more than m times
  139.      
  140.     Logical operators
  141.     XY  X followed by Y
  142.     X|Y     Either X or Y
  143.     (X)     X, as a capturing group
  144.      
  145.     Back references
  146.     \n  Whatever the nth capturing group matched
  147.      
  148.     Quotation
  149.     \   Nothing, but quotes the following character
  150.     \Q  Nothing, but quotes all characters until \E
  151.     \E  Nothing, but ends quoting started by \Q
  152.      
  153.     Special constructs (non-capturing)
  154.     (?:X)   X, as a non-capturing group
  155.     (?idmsux-idmsux)    Nothing, but turns match flags on - off
  156.     (?idmsux-idmsux:X)      X, as a non-capturing group with the given flags on - off
  157.     (?=X)   X, via zero-width positive lookahead
  158.     (?!X)   X, via zero-width negative lookahead
  159.     (?<=X)  X, via zero-width positive lookbehind
  160.     (?<!X)  X, via zero-width negative lookbehind
  161.     (?>X)   X, as an independent, non-capturing group
  162.     Backslashes, escapes, and quoting
  163.    
  164.     The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise
  165.     would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.
  166.    
  167.     It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct;
  168.     these are reserved for future extensions to the regular-expression language.
  169.     A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
  170.    
  171.     Backslashes within string literals in Java source code are interpreted as required by the Java Language Specification as either Unicode escapes or other character escapes.
  172.     It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler.
  173.     The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression,
  174.     while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and leads to a compile-time error;
  175.     in order to match the string (hello) the string literal "\\(hello\\)" must be used.
  176.     Character Classes
  177.    
  178.     Character classes may appear within other character classes, and may be composed by the union operator (implicit) and the intersection operator (&&).
  179.     The union operator denotes a class that contains every character that is in at least one of its operand classes.
  180.     The intersection operator denotes a class that contains every character that is in both of its operand classes.
  181.    
  182.     The precedence of character-class operators is as follows, from highest to lowest:
  183.    
  184.         1       Literal escape      \x
  185.         2       Grouping    [...]
  186.         3       Range   a-z
  187.         4       Union   [a-e][i-u]
  188.         5       Intersection    [a-z&&[aeiou]]
  189.    
  190.     Note that a different set of metacharacters are in effect inside a character class than outside a character class.
  191.     For instance, the regular expression . loses its special meaning inside a character class, while the expression - becomes a range forming metacharacter.
  192.     Line terminators
  193.    
  194.     A line terminator is a one- or two-character sequence that marks the end of a line of the input character sequence. The following are recognized as line terminators:
  195.    
  196.         * A newline (line feed) character ('\n'),
  197.         * A carriage-return character followed immediately by a newline character ("\r\n"),
  198.         * A standalone carriage-return character ('\r'),
  199.         * A next-line character ('\u0085'),
  200.         * A line-separator character ('\u2028'), or
  201.         * A paragraph-separator character ('\u2029).
  202.    
  203.     If UNIX_LINES mode is activated, then the only line terminators recognized are newline characters.
  204.    
  205.     The regular expression . matches any character except a line terminator unless the DOTALL flag is specified.
  206.    
  207.     By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence.
  208.     If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input.
  209.     When in MULTILINE mode $ matches just before a line terminator or the end of the input sequence.
  210.     Groups and capturing
  211.    
  212.     Capturing groups are numbered by counting their opening parentheses from left to right. In the expression ((A)(B(C))), for example, there are four such groups:
  213.    
  214.         1       ((A)(B(C)))
  215.         2       (A)
  216.         3       (B(C))
  217.         4       (C)
  218.    
  219.     Group zero always stands for the entire expression.
  220.    
  221.     Capturing groups are so named because, during a match, each subsequence of the input sequence that matches such a group is saved.
  222.     The captured subsequence may be used later in the expression, via a back reference, and may also be retrieved from the matcher once the match operation is complete.
  223.    
  224.     The captured input associated with a group is always the subsequence that the group most recently matched.
  225.     If a group is evaluated a second time because of quantification then its previously-captured value, if any, will be retained if the second evaluation fails.
  226.     Matching the string "aba" against the expression (a(b)?)+, for example, leaves group two set to "b". All captured input is discarded at the beginning of each match.
  227.    
  228.     Groups beginning with (? are pure, non-capturing groups that do not capture text and do not count towards the group total.
  229.     Unicode support
  230.    
  231.     This class is in conformance with Level 1 of Unicode Technical Standard #18: Unicode Regular Expression Guidelines, plus RL2.1 Canonical Equivalents.
  232.    
  233.     Unicode escape sequences such as \u2014 in Java source code are processed as described in ยง3.3 of the Java Language Specification.
  234.     Such escape sequences are also implemented directly by the regular-expression parser so that Unicode escapes can be used in expressions that are read from files
  235.     or from the keyboard. Thus the strings "\u2014" and "\\u2014", while not equal, compile into the same pattern, which matches the character with hexadecimal value 0x2014.
  236.    
  237.     Unicode blocks and categories are written with the \p and \P constructs as in Perl. \p{prop} matches if the input has the property prop,
  238.     while \P{prop} does not match if the input has that property. Blocks are specified with the prefix In, as in InMongolian.
  239.     Categories may be specified with the optional prefix Is: Both \p{L} and \p{IsL} denote the category of Unicode letters.
  240.     Blocks and categories can be used both inside and outside of a character class.
  241.    
  242.     The supported categories are those of The Unicode Standard in the version specified by the Character class.
  243.     The category names are those defined in the Standard, both normative and informative.
  244.     The block names supported by Pattern are the valid block names accepted and defined by UnicodeBlock.forName.
  245.    
  246.     Categories that behave like the java.lang.Character boolean ismethodname methods (except for the deprecated ones) are available through the same \p{prop} syntax
  247.     where the specified property has the name javamethodname.
  248.     Comparison to Perl 5
  249.    
  250.     The Pattern engine performs traditional NFA-based matching with ordered alternation as occurs in Perl 5.
  251.    
  252.     Perl constructs not supported by this class:
  253.    
  254.         - The conditional constructs (?{X}) and (?(condition)X|Y),
  255.         - The embedded code constructs (?{code}) and (??{code}),
  256.         - The embedded comment syntax (?#comment), and
  257.         - The preprocessing operations \l \\u, \L, and \U.
  258.    
  259.     Constructs supported by this class but not by Perl:
  260.    
  261.         - Possessive quantifiers, which greedily match as much as they can and do not back off, even when doing so would allow the overall match to succeed.
  262.         - Character-class union and intersection as described above.
  263.    
  264.     Notable differences from Perl:
  265.    
  266.         In Perl, \1 through \9 are always interpreted as back references; a backslash-escaped number greater than 9 is treated as a back reference
  267.         if at least that many subexpressions exist, otherwise it is interpreted, if possible, as an octal escape. In this class octal escapes must always begin with a zero.
  268.         In this class, \1 through \9 are always interpreted as back references, and a larger number is accepted as a back reference if at least that many subexpressions
  269.         exist at that point in the regular expression, otherwise the parser will drop digits until the number is smaller
  270.         or equal to the existing number of groups or it is one digit.
  271.        
  272.    
  273.         Perl uses the g flag to request a match that resumes where the last match left off.
  274.         This functionality is provided implicitly by the Matcher class: Repeated invocations of the find method will resume where the last match left off,
  275.         unless the matcher is reset.
  276.        
  277.         In Perl, embedded flags at the top level of an expression affect the whole expression.
  278.         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,
  279.         flags are restored at the end of the group just as in Perl.
  280.        
  281.         Perl is forgiving about malformed matching constructs, as in the expression *a, as well as dangling brackets, as in the expression abc],
  282.         and treats them as literals. This class also accepts dangling brackets but is strict about dangling metacharacters like +, ? and *,
  283.         and will throw a PatternSyntaxException if it encounters them.
  284.    
  285.     **/
  286.        
  287.        
  288.        
  289.        
  290.     /**
  291.    
  292.         Esempio1: pattern che restituisce il valore che segue la parola "azione"
  293.         .*azione/([^/]*).*
  294.         .* un numero da 0 a infinito di caratteri possono precedere la parola azione
  295.         dopo azione/ troviamo ([^/]*) Le parentesi tonde definiscono il pezzo di stringa che voglio che mi sia restituita
  296.         Le Parentesi quadre validano stringhe che contengono un numero da 0 a infinito di caratteri ma non contengono la /
  297.         L'ultimo pezzo di stringa puo essere qualsiasi cosa anche niente .*
  298.    
  299.         Esempio2: pattern che restituisce il valore di un parametro sapendo il nome
  300.         .+secondopar=([^&]*).*
  301.         .* un qualsiasi numero di caratteri anche 0 seguito dalla parola secondopar=.
  302.         La Parte successiva tra parentesi sara la sottostringa restituita, composta dai caratteri che seguono secondopar= fino a quando non trova un '&' che e' il carattere che delimita il valore del parametro dal successivo parametro
  303.    
  304.         N.B.
  305.         &amp; -> &
  306.         &lt; -> <
  307.         &gt; -> >
  308.         &quot; -> "
  309.         &apos; -> '
  310.         &#x??; -? Chr(??)
  311.         L'ultimo caso permette di rappresentare qualsiasi carattere tramite il suo codice ASCII, espresso in esadecimale,
  312.         al posto di ??. Quindi per esempio, per scrivere 'simbolo dell'euro' dovremo scrivere &#x80; ......
  313.      **/
  314.    
  315.    
  316.     private static final String CONTENUTO_NON_FORNITO = "Contenuto su cui effettuare una ricerca non fornita";
  317.     private static final String NESSUN_MATCH_TROVATO = "nessun match trovato";
  318.     private static RegExpException getErrorMessage(String method,String contenuto, String pattern, Exception e) {
  319.         return new RegExpException(method+" contenuto["+contenuto+"] pattern["+pattern+"] error: "+e.getMessage(),e);
  320.     }
  321.    
  322.    
  323.    
  324.     /**
  325.      * Estrae dal contenuto passata come parametro, i valori identificati dal parametro pattern
  326.      *
  327.      * @param contenuto contenuto su cui applicare la ricerca
  328.      * @param pattern Pattern di ricerca
  329.      * @return Array di Stringhe che matchano il pattern passato
  330.      *
  331.      */
  332.     public static List<String> getAllStringMatchPattern(String contenuto, String pattern) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  333.         return RegularExpressionEngine.getAllStringPatternEngine(contenuto,pattern,true,(RegularExpressionPatternCompileMode[])null);
  334.     }
  335.     public static List<String> getAllStringMatchPattern(String contenuto, String pattern, RegularExpressionPatternCompileMode ... compileModes) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  336.         return RegularExpressionEngine.getAllStringPatternEngine(contenuto,pattern,true,compileModes);
  337.     }
  338.     public static List<String> getAllStringMatchPattern(String contenuto, Pattern pattern) throws RegExpException,RegExpNotFoundException{
  339.         return RegularExpressionEngine.getAllStringPatternEngine(contenuto,pattern,true);
  340.     }
  341.    
  342.     public static List<String> getAllStringFindPattern(String contenuto, String pattern) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  343.         return RegularExpressionEngine.getAllStringPatternEngine(contenuto,pattern,false,(RegularExpressionPatternCompileMode[])null);
  344.     }
  345.     public static List<String> getAllStringFindPattern(String contenuto, String pattern, RegularExpressionPatternCompileMode ... compileModes) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  346.         return RegularExpressionEngine.getAllStringPatternEngine(contenuto,pattern,false,compileModes);
  347.     }
  348.     public static List<String> getAllStringFindPattern(String contenuto, Pattern pattern) throws RegExpException,RegExpNotFoundException{
  349.         return RegularExpressionEngine.getAllStringPatternEngine(contenuto,pattern,false);
  350.     }
  351.    
  352.     private static List<String> getAllStringPatternEngine(String contenuto, String pattern, boolean usingMatch, RegularExpressionPatternCompileMode ... compileModes) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  353.         Pattern p = validateEngine(pattern, compileModes);
  354.         return getAllStringPatternEngine(contenuto, p, usingMatch);
  355.     }
  356.     private static List<String> getAllStringPatternEngine(String contenuto, Pattern p, boolean usingMatch) throws RegExpException,RegExpNotFoundException{
  357.         if( (contenuto == null) || (contenuto.length() == 0))
  358.             throw new RegExpNotFoundException(CONTENUTO_NON_FORNITO);
  359.            
  360.         try{
  361.             Matcher matcher = p.matcher(contenuto);
  362.            
  363.             if(usingMatch) {
  364.                
  365.                 /*Attempts to match the entire region against the pattern: deve essere definito un pattern che considera tutto il contenuto*/
  366.                 return getAllStringPatternEngineMatch(matcher);
  367.             }
  368.             else {
  369.                
  370.                 /* Attempts to find the next subsequence of the input sequence that matches the pattern*/
  371.                 return getAllStringPatternEngineFind(matcher);
  372.             }

  373.         }catch(RegExpNotFoundException ex){
  374.             throw ex;
  375.         }catch(Exception e){
  376.             throw getErrorMessage("getAllStringMatchPattern", contenuto, p.toString(), e);
  377.         }
  378.     }
  379.     private static List<String> getAllStringPatternEngineMatch(Matcher matcher) throws RegExpNotFoundException{
  380.         /*Attempts to match the entire region against the pattern: deve essere definito un pattern che considera tutto il contenuto*/
  381.         String [] result = null;
  382.         if(matcher.matches()){
  383.             result = new String[matcher.groupCount()];
  384.             for(int i=1; i<=matcher.groupCount();i++){
  385.                 result[i-1]=matcher.group(i);
  386.             }
  387.         }
  388.         else{
  389.             throw new RegExpNotFoundException(NESSUN_MATCH_TROVATO);
  390.         }  
  391.        
  392.         if(result.length>0) {
  393.             List<String> l = new ArrayList<>();
  394.             l.addAll(Arrays.asList(result));
  395.             return l;
  396.         }
  397.        
  398.         throw new RegExpNotFoundException(NESSUN_MATCH_TROVATO);
  399.     }
  400.     private static List<String> getAllStringPatternEngineFind(Matcher matcher) throws RegExpNotFoundException{
  401.         List<String> l = new ArrayList<>();
  402.         while (matcher.find()) {
  403.             final String varname = matcher.group(1);
  404.             l.add(varname);
  405.         }
  406.        
  407.         if(!l.isEmpty()) {
  408.             return l;
  409.         }
  410.        
  411.         throw new RegExpNotFoundException(NESSUN_MATCH_TROVATO);
  412.     }


  413.     /**
  414.      * Estrae dal contenuto passata come parametro, il primo valore identificato dal parametro pattern
  415.      *
  416.      * @param contenuto contenuto su cui applicare la ricerca
  417.      * @param pattern Pattern di ricerca
  418.      * @return Prima Stringa che matcha il pattern passato
  419.      *
  420.      */
  421.     public static String getStringMatchPattern(String contenuto, String pattern) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  422.         return RegularExpressionEngine.getStringPatternEngine(contenuto, pattern, true, (RegularExpressionPatternCompileMode[])null);
  423.     }
  424.     public static String getStringMatchPattern(String contenuto, String pattern, RegularExpressionPatternCompileMode ... compileModes) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  425.         return RegularExpressionEngine.getStringPatternEngine(contenuto, pattern, true, compileModes);
  426.     }
  427.     public static String getStringMatchPattern(String contenuto, Pattern pattern) throws RegExpException,RegExpNotFoundException{
  428.         return RegularExpressionEngine.getStringPatternEngine(contenuto, pattern, true);
  429.     }
  430.    
  431.     public static String getStringFindPattern(String contenuto, String pattern) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  432.         return RegularExpressionEngine.getStringPatternEngine(contenuto, pattern, false, (RegularExpressionPatternCompileMode[])null);
  433.     }
  434.     public static String getStringFindPattern(String contenuto, String pattern, RegularExpressionPatternCompileMode ... compileModes) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  435.         return RegularExpressionEngine.getStringPatternEngine(contenuto, pattern, false, compileModes);
  436.     }
  437.     public static String getStringFindPattern(String contenuto, Pattern pattern) throws RegExpException,RegExpNotFoundException{
  438.         return RegularExpressionEngine.getStringPatternEngine(contenuto, pattern, false);
  439.     }
  440.    
  441.     private static String getStringPatternEngine(String contenuto, String pattern, boolean usingMatch, RegularExpressionPatternCompileMode ... compileModes) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  442.         Pattern p = validateEngine(pattern, compileModes);
  443.         return getStringPatternEngine(contenuto, p, usingMatch);
  444.     }
  445.     private static String getStringPatternEngine(String contenuto, Pattern p, boolean usingMatch) throws RegExpException,RegExpNotFoundException{
  446.        
  447.         if( (contenuto == null) || (contenuto.length() == 0))
  448.             throw new RegExpNotFoundException(CONTENUTO_NON_FORNITO);
  449.        
  450.         try{
  451.             Matcher matcher = p.matcher(contenuto);
  452.             String result = null;
  453.            
  454.             boolean esito = false;
  455.             if(usingMatch) {
  456.                 esito = matcher.matches(); /*Attempts to match the entire region against the pattern: deve essere definito un pattern che considera tutto il contenuto*/
  457.             }
  458.             else {
  459.                 esito = matcher.find(); /* Attempts to find the next subsequence of the input sequence that matches the pattern*/
  460.             }
  461.            
  462.             if(esito){
  463.                 result = matcher.group(1);
  464.             }
  465.             else{
  466.                 throw new RegExpNotFoundException(NESSUN_MATCH_TROVATO);
  467.             }
  468.            
  469.             if("".equals(result)){
  470.                 throw new RegExpNotFoundException(NESSUN_MATCH_TROVATO);
  471.             }
  472.            
  473.             return result;
  474.         }catch(RegExpNotFoundException ex){
  475.             throw ex;
  476.         }catch(Exception e){
  477.             throw getErrorMessage("getStringMatchPattern", contenuto, p.toString(), e);
  478.         }
  479.     }


  480.    
  481.    
  482.     /**
  483.      * @param contenuto contenuto su cui applicare la ricerca
  484.      * @param pattern Pattern di ricerca
  485.      * @return indicazione se il contenuto rispetto il pattern
  486.      * @throws ExpressionException
  487.      * @throws ExpressionNotFoundException
  488.      */
  489.     public static boolean isMatch(String contenuto, String pattern) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  490.         return RegularExpressionEngine.isMatchEngine(contenuto, pattern, true, (RegularExpressionPatternCompileMode[])null);
  491.     }
  492.     public static boolean isMatch(String contenuto, String pattern, RegularExpressionPatternCompileMode ... compileModes) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  493.         return RegularExpressionEngine.isMatchEngine(contenuto, pattern, true, compileModes);
  494.     }
  495.     public static boolean isFind(String contenuto, String pattern) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  496.         return RegularExpressionEngine.isMatchEngine(contenuto, pattern, false, (RegularExpressionPatternCompileMode[])null);
  497.     }
  498.     public static boolean isFind(String contenuto, String pattern, RegularExpressionPatternCompileMode ... compileModes) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  499.         return RegularExpressionEngine.isMatchEngine(contenuto, pattern, false, compileModes);
  500.     }
  501.     private static boolean isMatchEngine(String contenuto, String pattern, boolean usingMatch, RegularExpressionPatternCompileMode ... compileModes) throws RegExpException,RegExpNotValidException,RegExpNotFoundException{
  502.            
  503.         Pattern p = validateEngine(pattern, compileModes);
  504.        
  505.         if( (contenuto == null) || (contenuto.length() == 0))
  506.             throw new RegExpNotFoundException(CONTENUTO_NON_FORNITO);
  507.        
  508.         try{
  509.             Matcher matcher = p.matcher(contenuto);
  510.             if(usingMatch) {
  511.                 return matcher.matches();
  512.             }
  513.             else {
  514.                 return matcher.find();
  515.             }
  516.         }catch(Exception e){
  517.             throw getErrorMessage("isMatch", contenuto, pattern, e);
  518.         }
  519.     }


  520.    
  521.     /* ---------- VALIDATORE -------------- */
  522.    
  523.     public static void validate(String pattern) throws RegExpNotValidException{
  524.         validateEngine(pattern);
  525.     }
  526.     public static void validate(String pattern, RegularExpressionPatternCompileMode ... compileModes) throws RegExpNotValidException{
  527.         validateEngine(pattern, compileModes);
  528.     }
  529.     private static Pattern validateEngine(String pattern, RegularExpressionPatternCompileMode ... compileModes) throws RegExpNotValidException{
  530.        
  531.         if( (pattern == null) || (pattern.length() == 0))
  532.             throw new RegExpNotValidException("Pattern di ricerca non fornito");
  533.         try{
  534.             pattern = pattern.trim();
  535.             return createPatternEngine(pattern, compileModes);
  536.         }catch(Exception e){
  537.             throw new RegExpNotValidException("Validazione del pattern indicato ["+pattern+"] fallita: "+e.getMessage(),e);
  538.         }
  539.        
  540.     }
  541.    
  542.    
  543.     /* UTILITY */
  544.    
  545.     public static  Pattern createPatternEngine(String pattern,RegularExpressionPatternCompileMode ... compileModes){
  546.         Pattern p = null;
  547.         if(compileModes!=null && compileModes.length>0){
  548.             int mode = compileModes[0].getPatternCompileMode();
  549.             for(int i = 1; i<compileModes.length; i++){
  550.                 mode = mode | compileModes[i].getPatternCompileMode();
  551.             }
  552.             p = Pattern.compile(pattern,mode);
  553.         }else{
  554.             p = Pattern.compile(pattern);
  555.         }
  556.         return p;
  557.     }
  558. }