1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License (the "License"). 6 * You may not use this file except in compliance with the License. 7 * 8 * See LICENSE.txt included in this distribution for the specific 9 * language governing permissions and limitations under the License. 10 * 11 * When distributing Covered Code, include this CDDL HEADER in each 12 * file and include the License file at LICENSE.txt. 13 * If applicable, add the following below this CDDL HEADER, with the 14 * fields enclosed by brackets "[]" replaced with your own identifying 15 * information: Portions Copyright [yyyy] [name of copyright owner] 16 * 17 * CDDL HEADER END 18 */ 19 20 /* 21 * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. 22 */ 23 package org.opengrok.indexer.configuration; 24 25 import java.util.regex.Pattern; 26 import java.util.regex.PatternSyntaxException; 27 28 public class PatternUtil { PatternUtil()29 private PatternUtil() { 30 // private to enforce static 31 } 32 33 /** 34 * A check if a pattern contains at least one pair of parentheses meaning 35 * that there is at least one capture group. This group must not be empty. 36 */ 37 private static final String PATTERN_SINGLE_GROUP = ".*\\([^\\)]+\\).*"; 38 /** 39 * Error string for invalid patterns without a single group. This is passed 40 * as a first argument to the constructor of PatternSyntaxException and in 41 * the output it is followed by the invalid pattern. 42 * 43 * @see PatternSyntaxException 44 * @see #PATTERN_SINGLE_GROUP 45 */ 46 private static final String PATTERN_MUST_CONTAIN_GROUP = "The pattern must contain at least one non-empty group -"; 47 48 /** 49 * Check and compile the bug pattern. 50 * 51 * @param pattern the new pattern 52 * @throws PatternSyntaxException when the pattern is not a valid regexp or 53 * does not contain at least one capture group and the group does not 54 * contain a single character 55 */ compilePattern(String pattern)56 public static String compilePattern(String pattern) throws PatternSyntaxException { 57 if (!pattern.matches(PATTERN_SINGLE_GROUP)) { 58 throw new PatternSyntaxException(PATTERN_MUST_CONTAIN_GROUP, pattern, 0); 59 } 60 return Pattern.compile(pattern).toString(); 61 } 62 } 63