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:org.bremersee.common.spring.autoconfigure.LdaptiveInMemoryDirectoryServerProperties.java

public String[] getLdifLocationsAsArray() {
    if (StringUtils.hasText(ldifLocations)) {
        String[] values = ldifLocations.split(Pattern.quote(","));
        return Arrays.stream(values).map(String::trim).toArray(size -> new String[size]);
    }/*ww w.ja v  a2  s. com*/
    return new String[0];
}

From source file:gov.sbs.blame.BlamePlugin.java

private Map<Integer, String> getWhoDidIt(String command) {

    Map<Integer, String> lineAndPerson = new HashMap<Integer, String>();

    String nameRegex = Pattern.quote("(") + "(.*?)" + Pattern.quote(" ");
    Pattern namePattern = Pattern.compile(nameRegex);

    Pattern linePattern = Pattern.compile("\\s(\\w+)$");

    Process p;/* w  w  w  .  ja  v  a 2  s .c  om*/
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";
        while ((line = reader.readLine()) != null) {
            //Need to clean the line up first to avoid picking up things in the code
            String[] cleanLine = line.split("\\)");
            line = cleanLine[0];

            String name = "";
            Integer lineNumber = null;

            Matcher nameMatcher = namePattern.matcher(line);
            while (nameMatcher.find()) {
                name = nameMatcher.group(1); // Since (.*?) is capturing group 1

            }

            Matcher lineMatcher = linePattern.matcher(line.trim());
            while (lineMatcher.find()) {
                lineNumber = new Integer(lineMatcher.group().trim());
            }

            lineAndPerson.put(lineNumber, name);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return lineAndPerson;
}

From source file:com.commander4j.util.JUtility.java

public static String encodeControlChars(String input) {
    String result = input;//  w  w  w  . j a  v  a  2s .  c om

    result = result.replaceAll(Pattern.quote("<NUL>"), "\u0000");
    result = result.replaceAll(Pattern.quote("<SOH>"), "\u0001");
    result = result.replaceAll(Pattern.quote("<STX>"), "\u0002");
    result = result.replaceAll(Pattern.quote("<ETX>"), "\u0003");
    result = result.replaceAll(Pattern.quote("<EOT>"), "\u0004");
    result = result.replaceAll(Pattern.quote("<ENQ>"), "\u0005");
    result = result.replaceAll(Pattern.quote("<ACK>"), "\u0006");
    result = result.replaceAll(Pattern.quote("<BEL>"), "\u0007");
    result = result.replaceAll(Pattern.quote("<BS>"), "\u0008");
    result = result.replaceAll(Pattern.quote("<HT>"), "\u0009");
    result = result.replaceAll(Pattern.quote("<LF>"), "\n");
    result = result.replaceAll(Pattern.quote("<VT>"), "\u000B");
    result = result.replaceAll(Pattern.quote("<FF>"), "\u000C");
    result = result.replaceAll(Pattern.quote("<CR>"), "\r");
    result = result.replaceAll(Pattern.quote("<SO>"), "\u000E");
    result = result.replaceAll(Pattern.quote("<SI>"), "\u000F");
    result = result.replaceAll(Pattern.quote("<DLE>"), "\u0010");
    result = result.replaceAll(Pattern.quote("<DC1>"), "\u0011");
    result = result.replaceAll(Pattern.quote("<DC2>"), "\u0012");
    result = result.replaceAll(Pattern.quote("<DC3>"), "\u0013");
    result = result.replaceAll(Pattern.quote("<DC4>"), "\u0014");
    result = result.replaceAll(Pattern.quote("<NAK>"), "\u0015");
    result = result.replaceAll(Pattern.quote("<SYN>"), "\u0016");
    result = result.replaceAll(Pattern.quote("<ETB>"), "\u0017");
    result = result.replaceAll(Pattern.quote("<CAN>"), "\u0018");
    result = result.replaceAll(Pattern.quote("<EM>"), "\u0019");
    result = result.replaceAll(Pattern.quote("<SUB>"), "\u001A");
    result = result.replaceAll(Pattern.quote("<ESC>"), "\u001B");
    result = result.replaceAll(Pattern.quote("<FS>"), "\u001C");
    result = result.replaceAll(Pattern.quote("<GS>"), "\u001D");
    result = result.replaceAll(Pattern.quote("<RS>"), "\u001E");
    result = result.replaceAll(Pattern.quote("<US>"), "\u001F");

    return result;
}

From source file:GIST.IzbirkomExtractor.TableExtractor.java

/**
     * Cleaning up leftover of HTML code from the cell content.
     * /*from  w w  w  .  java2 s  . co  m*/
     * @param cell_content HTML code contains in the table cell 
     * @return an array list containing each line of the cell_content withh all HTML markup removed
     */
    private ArrayList<String> cleanLeftoverHTML(Element cell_content) {

        ArrayList<String> streets_and_numbers = new ArrayList<String>();

        /* <div>s designate separate lines inside the table cell */
        for (Element addr_line : cell_content.getElementsByTag("div")) {

            /* skip empty address lines */
            String addr_line_text = cleanupUNICODE(addr_line.text());
            if (StringUtils.isBlank(addr_line_text))
                continue;

            /* <strong> is not particularly useful, but can designate placement of simple separators like space */
            Elements streets = addr_line.getElementsByTag("strong");
            if (!streets.isEmpty()) {
                addr_line_text = addr_line_text.replaceFirst(Pattern.quote(streets.text()),
                        " " + streets.text() + " ");
            }

            streets_and_numbers.add(addr_line_text);
        }
        return streets_and_numbers;
    }

From source file:net.sf.logsaw.dialect.websphere.WebsphereDialect.java

private Pattern getInternalPattern() throws CoreException {
    StringBuilder sb = new StringBuilder();
    sb.append(Pattern.quote("[")); //$NON-NLS-1$
    // Timestamp//from www .  ja  va 2  s  .  c o m
    sb.append("(.*)"); //$NON-NLS-1$
    sb.append(Pattern.quote("] ")); //$NON-NLS-1$
    // Thread ID
    sb.append("([0-9a-f]{8})"); //$NON-NLS-1$
    sb.append(Pattern.quote(" ")); //$NON-NLS-1$
    // Short Name
    sb.append("(.{13})"); //$NON-NLS-1$
    sb.append(Pattern.quote(" ")); //$NON-NLS-1$
    // Event Type
    sb.append("([AIWEFORuZ])"); //$NON-NLS-1$
    sb.append(Pattern.quote(" ")); //$NON-NLS-1$
    // Class Name (optional)
    sb.append("([^\\s]*)"); //$NON-NLS-1$
    sb.append(Pattern.quote(" ")); //$NON-NLS-1$
    // Method Name (optional)
    sb.append("([^\\s]*)"); //$NON-NLS-1$
    sb.append(Pattern.quote(" ")); //$NON-NLS-1$
    // Message
    sb.append("(.*)"); //$NON-NLS-1$
    return Pattern.compile(sb.toString());
}

From source file:net.sf.logsaw.dialect.pattern.APatternDialect.java

/**
 * Converts the given external pattern to the internal Regex pattern using the specified conversion rules.
 * @param externalPattern the external pattern
 * @param patternTranslator the conversion pattern translator
 * @param rules the conversion rules/*from   w ww .  java  2 s .co m*/
 * @return the internal pattern
 * @throws CoreException if an error occurred
 */
protected String toRegexPattern(String externalPattern, IConversionPatternTranslator patternTranslator,
        List<ConversionRule> rules, boolean firstLineOnly) throws CoreException {
    // Build the internal Regex pattern
    StringBuilder sb = new StringBuilder();
    int idx = 0;
    for (ConversionRule rule : rules) {
        if (firstLineOnly && rule.isLineBreak()) {
            // That's it
            return sb.toString();
        }
        if (rule.getBeginIndex() > idx) {
            // Escape chars with special meaning
            sb.append(Pattern.quote(externalPattern.substring(idx, rule.getBeginIndex())));
        }
        idx = rule.getBeginIndex();
        String regex = patternTranslator.getRegexPatternForRule(rule);
        Assert.isNotNull(regex, "regex"); //$NON-NLS-1$
        sb.append(regex);
        idx += rule.getLength();
    }
    if (externalPattern.length() > idx) {
        // Append suffix
        sb.append(Pattern.quote(externalPattern.substring(idx)));
    }
    return sb.toString();
}

From source file:de.micromata.genome.gwiki.page.search.expr.SearchUtils.java

@Deprecated
public static String sampleToHtmlNew(String text, List<String> words) {
    String ap = Pattern.quote("<!--KW:XXX-->");
    String ep = Pattern.quote("<!--KW-->");
    // TODO gwiki geht nicht mit umlauten, da words normalisiert sind.
    // StringBuilder sb = new StringBuilder();
    for (String w : words) {
        String nw = NormalizeUtils.normalize(w);
        String app = StringUtils.replace(ap, "XXX", nw);
        String reg = app + "(.+?)" + ep;
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(text);
        while (m.find() == true) {
            int start = m.start(1);
            int end = m.end(1);
            String t = m.group(1);
            text = text.substring(0, start) + "<b><strong><big>" + t + "</big></strong></b>"
                    + text.substring(end);
        }//from  w w  w  .j  a  va2 s  . c  o  m
        // text = StringUtils.replace(text, w, "<b><strong><big>" + w + "</big></strong></b>");
    }
    return text;
}

From source file:com.logsniffer.reader.support.FormattedTextReader.java

/**
 * @param formatPattern//w  w  w  . ja  v a2s.c o m
 *            the formatPattern to set
 */
@Override
protected void init() throws FormatException {
    super.init();
    if (parsingPattern == null) {
        // Only if not yet parsed
        if (formatPattern != null) {
            final ArrayList<Specifier> specs = new ArrayList<Specifier>();
            final StringBuilder parsingPatternStr = new StringBuilder();
            final Matcher m = SPECIFIER_PATTERN.matcher(formatPattern);
            int leftPos = 0;
            while (m.find()) {
                if (m.start() > leftPos) {
                    parsingPatternStr.append(Pattern.quote(formatPattern.substring(leftPos, m.start())));
                }
                leftPos = m.end();
                final String minWidthStr = m.group(2);
                final String maxWidthStr = m.group(4);
                final String specName = m.group(5);
                final String specModifier = m.group(7);
                int minWidth = -1;
                if (minWidthStr != null && minWidthStr.length() > 0) {
                    minWidth = Integer.parseInt(minWidthStr);
                }
                int maxWidth = -1;
                if (maxWidthStr != null && maxWidthStr.length() > 0) {
                    maxWidth = Integer.parseInt(maxWidthStr);
                }
                Specifier spec = null;
                for (final Specifier specTest : createSupportedSpecifiers()) {
                    if (specTest.getSpecifierKey().equals(specName)) {
                        spec = specTest;
                        break;
                    }
                }
                if (spec == null) {
                    logger.debug(
                            "Format specifier {} in pattern '{}' is unknown and will be parsed as simple text pattern",
                            specName, formatPattern);
                    spec = new ArbitraryTextSpecifier(specName, false);
                } else if (spec instanceof IgnoreSpecifier) {
                    logger.debug("Format specifier '{}' in pattern '{}' is ignored", specName, formatPattern);
                    continue;
                }
                spec.setMaxWidth(maxWidth);
                spec.setMinWidth(minWidth);
                spec.setModifier(specModifier);
                parsingPatternStr.append("(");
                parsingPatternStr.append(spec.getRegex());
                parsingPatternStr.append(")");
                spec.fieldName = specifiersFieldMapping.get(specName);
                if (StringUtils.isBlank(spec.fieldName)) {
                    spec.fieldName = specName;
                }
                specs.add(spec);
            }
            parsingPatternStr.append(Pattern.quote(formatPattern.substring(leftPos)));
            parsingPattern = Pattern.compile(parsingPatternStr.toString());
            parsingSpecifiers = specs.toArray(new Specifier[specs.size()]);
            logger.debug("Prepared parsing pattern '{}' for log4j conversion pattern: {}", parsingPattern,
                    formatPattern);
        } else {
            parsingSpecifiers = null;
            parsingPattern = null;
        }
    }
}

From source file:it.wingstech.csslesser.LessifyMojo.java

private String inline(File f, String prefix) throws MojoExecutionException {
    if (f.isFile()) {
        getLog().info("Inlining file: " + f.getAbsolutePath() + " ...");
        try {//from w  w w  . j a  v a  2 s  . c  o  m
            String content = FileUtils.readFileToString(f);
            Pattern p = Pattern.compile("(" + Pattern.quote("@import url(") + "[\\'\\\"]?)(.*?)([\\'\\\"]?"
                    + Pattern.quote(");") + ")");

            Matcher m = p.matcher(content);
            StringBuffer sb = new StringBuffer();

            while (m.find() == true) {
                String url = m.group(2);
                getLog().info("   importing file: " + url + " ...");
                String cPrefix = ".";
                int ix = url.lastIndexOf("/");
                if (ix > 0) {
                    cPrefix = url.substring(0, ix);
                }

                String inputReplacement = inline(
                        new File(f.getParentFile().getAbsolutePath() + File.separator + m.group(2)), cPrefix);
                m.appendReplacement(sb, inputReplacement);
            }
            m.appendTail(sb);

            String result = sb.toString();

            FileUtils.writeStringToFile(f, result);

            StringBuffer sbIncludeImages = new StringBuffer();
            Pattern pImgReplacement = Pattern.compile(
                    "(" + Pattern.quote("url(") + "[\\'\\\"]?)(.*?)([\\'\\\"]?" + Pattern.quote(")") + ")");
            Matcher mImgReplacement = pImgReplacement.matcher(result);
            while (mImgReplacement.find() == true) {
                String urlImage = mImgReplacement.group(2);

                if (!urlImage.startsWith("/")) {
                    urlImage = prefix + "/" + urlImage;
                }
                mImgReplacement.appendReplacement(sbIncludeImages, "url('" + urlImage + "')");

            }
            mImgReplacement.appendTail(sbIncludeImages);

            return sbIncludeImages.toString();

        } catch (Exception ex) {
            throw new MojoExecutionException(ex.getMessage() + " on file " + f.getAbsolutePath(), ex);
        }
    }
    return "";
}

From source file:fr.fastconnect.factory.tibco.bw.maven.source.AbstractProjectsListMojo.java

/**
 * <p>/*from   w ww . j  av a2s . c om*/
 * 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 '\'.
 * </p>
 * 
 * @param targetPath targetPath is calculated to this file
 * @param basePath basePath is calculated from this file
 * @param pathSeparator 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.
    StringBuffer common = new StringBuffer();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex] + 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 PathResolutionException("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;
    }

    StringBuffer relative = new StringBuffer();

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

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