com.sun.enterprise.util.RegexUtil Maven / Gradle / Ivy
/*
* Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.enterprise.util;
/** Provides some regex utilities.
* @author Kedar Mhaswade ([email protected])
* @since GF 3.1
*/
public class RegexUtil {
/**
* Convert a shell style glob regular expression to a
* Java regular expression.
* Code from: http://stackoverflow.com/questions/1247772
*/
public static String globToRegex(String line) {
line = line.trim();
int strLen = line.length();
StringBuilder sb = new StringBuilder(strLen);
boolean escaping = false;
int inCurlies = 0;
for (char currentChar : line.toCharArray()) {
switch (currentChar) {
case '*':
if (escaping)
sb.append("\\*");
else
sb.append(".*");
escaping = false;
break;
case '?':
if (escaping)
sb.append("\\?");
else
sb.append('.');
escaping = false;
break;
case '.':
case '(':
case ')':
case '+':
case '|':
case '^':
case '$':
case '@':
case '%':
sb.append('\\');
sb.append(currentChar);
escaping = false;
break;
case '\\':
if (escaping) {
sb.append("\\\\");
escaping = false;
} else
escaping = true;
break;
case '{':
if (escaping) {
sb.append("\\{");
} else {
sb.append('(');
inCurlies++;
}
escaping = false;
break;
case '}':
if (inCurlies > 0 && !escaping) {
sb.append(')');
inCurlies--;
} else if (escaping)
sb.append("\\}");
else
sb.append("}");
escaping = false;
break;
case ',':
if (inCurlies > 0 && !escaping)
sb.append('|');
else if (escaping)
sb.append("\\,");
else
sb.append(",");
break;
default:
escaping = false;
sb.append(currentChar);
}
}
return sb.toString();
}
}