Example usage for java.util.regex Pattern quote

List of usage examples for java.util.regex Pattern quote

Introduction

In this page you can find the example usage for java.util.regex Pattern quote.

Prototype

public static String quote(String s) 

Source Link

Document

Returns a literal pattern String for the specified String .

Usage

From source file:io.cloudslang.content.utils.CollectionUtilities.java

/**
 * Splits the stringArray by the delimiter into an array of strings ignoring the escaped delimiters
 *
 * @param stringArray the string to be split
 * @param delimiter   the delimiter by which to split the stringArray
 * @return an array of Strings/*from   w ww.  j  a va  2 s  .  c  om*/
 */
@NotNull
public static String[] toArray(@Nullable final String stringArray, @NotNull final String delimiter) {
    if (StringUtils.isEmpty(stringArray)) {
        return new String[0];
    }
    final String regex = "(?<!\\\\)" + Pattern.quote(delimiter);
    return stringArray.split(regex);
}

From source file:com.threewks.thundr.route.redirect.Redirect.java

public String getRedirectTo(Map<String, String> pathVars) {
    String finalRedirect = redirectTo;

    Matcher matcher = Route.PathParameterPattern.matcher(redirectTo);
    while (matcher.find()) {
        String token = matcher.group(1);
        finalRedirect = finalRedirect.replaceAll(Pattern.quote("{" + token + "}"),
                Matcher.quoteReplacement(StringUtils.trimToEmpty(pathVars.get(token))));
    }//from   w  ww  .j  a  v a2s  . co m
    return finalRedirect;
}

From source file:ezbake.deployer.impl.Files.java

public static File relativize(File base, File target) {
    String[] baseComponents;/* w w  w .j av a2  s  .c om*/
    String[] targetComponents;
    try {
        baseComponents = base.getCanonicalPath().split(Pattern.quote(File.separator));
        targetComponents = target.getCanonicalPath().split(Pattern.quote(File.separator));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // skip common components
    int index = 0;
    for (; index < targetComponents.length && index < baseComponents.length; ++index) {
        if (!targetComponents[index].equals(baseComponents[index]))
            break;
    }

    StringBuilder result = new StringBuilder();
    if (index != baseComponents.length) {
        // backtrack to base directory
        for (int i = index; i < baseComponents.length; ++i)
            result.append("..").append(File.separator);
    }
    for (; index < targetComponents.length; ++index)
        result.append(targetComponents[index]).append(File.separator);
    if (!target.getPath().endsWith("/") && !target.getPath().endsWith("\\")) {
        // remove final path separator
        result.delete(result.length() - File.separator.length(), result.length());
    }
    return new File(result.toString());
}

From source file:gobblin.util.recordcount.LateFileRecordCountProvider.java

/**
 * Remove the late components in the path added by {@link LateFileRecordCountProvider}.
 *//*  ww w  .  ja  va 2  s. c o  m*/
public static Path restoreFilePath(Path path) {
    return new Path(path.getName().replaceAll(Pattern.quote(LATE_COMPONENT) + "[\\d]*", EMPTY_STRING));
}

From source file:forge.util.FileSection.java

public static Map<String, String> parseToMap(final String line, final String kvSeparator,
        final String pairSeparator) {
    Map<String, String> result = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    if (!StringUtils.isEmpty(line)) {
        final String[] pairs = line.split(Pattern.quote(pairSeparator));
        final Pattern splitter = Pattern.compile(Pattern.quote(kvSeparator));

        for (final String dd : pairs) {
            final String[] v = splitter.split(dd, 2);
            result.put(v[0].trim(), v.length > 1 ? v[1].trim() : "");
        }/*from  ww w  .  ja  va  2 s . co  m*/
    }
    return result;
}

From source file:com.badlogic.gdx.box2deditor.utils.FileUtils.java

/**
 * Get the relative path from one file to another, specifying the directory separator.
 * If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or
 * '\'.//from ww w  . j  ava  2s  .  co  m
 *
 * @param target targetPath is calculated to this file
 * @param base basePath is calculated from this file
 * @param separator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example)
 * @return
 */
public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {
    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

    // Undo the changes to the separators made by normalization
    if (pathSeparator.equals("/")) {
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

    } else if (pathSeparator.equals("\\")) {
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);

    } else {
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuilder common = new StringBuilder();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex]).append(pathSeparator);
        commonIndex++;
    }

    if (commonIndex == 0) {
        // No single common path element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        throw new NoCommonPathFoundException("No common path element found for '" + normalizedTargetPath
                + "' and '" + normalizedBasePath + "'");
    }

    // The number of directories we have to backtrack depends on whether the base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    //
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
    // the resource referred to by this path may not actually exist, but it's the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();

    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }

    StringBuilder relative = new StringBuilder();

    if (base.length != commonIndex) {
        int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

        for (int i = 0; i < numDirsUp; i++) {
            relative.append("..").append(pathSeparator);
        }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
}

From source file:core.com.qiniu.util.AwsHostNameUtils.java

/**
 * Attempts to parse the region name from an endpoint based on conventions
 * about the endpoint format./*w w  w  .ja va  2  s. c o  m*/
 *
 * @param host the hostname to parse
 * @param serviceHint an optional hint about the service for the endpoint
 * @return the region parsed from the hostname, or &quot;us-east-1&quot; if
 *         no region information could be found
 */
public static String parseRegionName(final String host, final String serviceHint) {

    if (host == null) {
        throw new IllegalArgumentException("hostname cannot be null");
    }
    String regionNameInInternalConfig = parseRegionNameByInternalConfig(host);
    if (regionNameInInternalConfig != null) {
        return regionNameInInternalConfig;
    }

    if (host.endsWith(".amazonaws.com")) {
        int index = host.length() - ".amazonaws.com".length();
        return parseStandardRegionName(host.substring(0, index));
    }

    if (serviceHint != null) {
        // If we have a service hint, look for 'service.[region]' or
        // 'service-[region]' in the endpoint's hostname.
        Pattern pattern = Pattern.compile("^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\.");

        Matcher matcher = pattern.matcher(host);
        if (matcher.find()) {
            return matcher.group(1);
        }
    }

    // Endpoint is totally non-standard; guess us-east-1 for lack of a
    // better option.

    return "us-east-1";
}

From source file:aurelienribon.utils.io.FilenameHelper.java

/**
 * Gets the relative path from one file to another.
 *//*from w w w .j av a 2s .  c om*/
public static String getRelativePath(String targetPath, String basePath) {
    if (basePath == null || basePath.equals(""))
        return targetPath;
    if (targetPath == null || targetPath.equals(""))
        return "";

    String pathSeparator = File.separator;

    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

    if (basePath.equals(targetPath))
        return "";

    // Undo the changes to the separators made by normalization
    if (pathSeparator.equals("/")) {
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

    } else if (pathSeparator.equals("\\")) {
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);

    } else {
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuilder common = new StringBuilder();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex]).append(pathSeparator);
        commonIndex++;
    }

    if (commonIndex == 0) {
        return targetPath;
    }

    // The number of directories we have to backtrack depends on whether the base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    //
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
    // the resource referred to by this path may not actually exist, but it's the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();

    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }

    StringBuilder relative = new StringBuilder();

    if (base.length != commonIndex) {
        int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

        for (int i = 0; i < numDirsUp; i++) {
            relative.append("..").append(pathSeparator);
        }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
}

From source file:com.mirth.connect.connectors.mllp.ResponseAck.java

public ResponseAck(String ackMessageString) {
    // save the incoming ack message
    this.ackMessageString = ackMessageString;

    try {// w  w  w .j  a v  a2s  .  com
        if (ackMessageString.startsWith("<")) {
            HL7v2Header headerData = HL7v2XMLQuickParser.getInstance().processMSA(ackMessageString);
            if (headerData.getParseError() == null) {
                setStatus(headerData.getAcknowledgmentCode(), headerData.getAckMessageControlId(),
                        headerData.getAckTextMessage(), headerData.getError());
            } else {
                throw new Exception(headerData.getParseError());
            }
        } else {
            char segmentDelim = '\r';
            char fieldDelim = ackMessageString.charAt(3); // Usually |

            Pattern segmentPattern = Pattern.compile(Pattern.quote(String.valueOf(segmentDelim)));
            Pattern fieldPattern = Pattern.compile(Pattern.quote(String.valueOf(fieldDelim)));

            String msa1 = "";
            String msa2 = "";
            String msa3 = "";
            String err1 = "";
            String[] segments = segmentPattern.split(ackMessageString);
            for (String segment : segments) {
                String[] fields = fieldPattern.split(segment);

                if (fields[0].equals("MSA")) {
                    if (fields.length > 1) {
                        msa1 = fields[1];
                    }
                    if (fields.length > 3) {
                        msa3 = fields[3];
                    }
                } else if (fields[0].equals("ERR")) {
                    if (fields.length > 1) {
                        err1 = fields[1];
                    }
                }
            }

            setStatus(msa1, msa2, msa3, err1);
        }

        logger.debug("ACK: " + ackMessageString);
    } catch (Exception e) {
        errorDescription = " Message is not a valid ACK";
        errorDescription += "\n" + e + "\n" + ackMessageString;
    }
}

From source file:com.seajas.search.contender.service.modifier.ModifierFilterProcessor.java

/**
 * Process the given reader using this filter.
 * //from ww w. jav  a2  s. com
 * @param filter
 * @param reader
 * @return Reader
 * @throws IOException
 */
public Reader process(final ModifierFilter filter, final Reader reader) throws IOException {
    StringBuffer stringBuffer = new StringBuffer();

    for (int c; (c = reader.read()) != -1;)
        stringBuffer.append((char) c);

    reader.close();

    if (!filter.getIsExpression()) {
        Pattern pattern = Pattern.compile(
                Pattern.quote(filter.getFragmentStart()) + ".*" + Pattern.quote(filter.getFragmentEnd()),
                Pattern.DOTALL | Pattern.CASE_INSENSITIVE);

        return new StringReader(
                pattern.matcher(stringBuffer).replaceAll(filter.getFragmentStart() + filter.getFragmentEnd()));
    } else {
        Matcher startMatcher = Pattern.compile(filter.getFragmentStart(), Pattern.CASE_INSENSITIVE)
                .matcher(stringBuffer),
                endMatcher = Pattern.compile(filter.getFragmentEnd(), Pattern.CASE_INSENSITIVE)
                        .matcher(stringBuffer);

        while (startMatcher.find() && endMatcher.find(startMatcher.end()))
            if (startMatcher.end() != endMatcher.start()) {
                stringBuffer.delete(startMatcher.end(), endMatcher.start());

                startMatcher.reset();
                endMatcher.reset();
            }

        // Store the result

        return new StringReader(stringBuffer.toString());
    }
}