Example usage for java.util.regex Pattern DOTALL

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

Introduction

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

Prototype

int DOTALL

To view the source code for java.util.regex Pattern DOTALL.

Click Source Link

Document

Enables dotall mode.

Usage

From source file:com.norconex.importer.handler.transformer.impl.StripBetweenTransformer.java

@Override
protected void transformStringContent(String reference, StringBuilder content, ImporterMetadata metadata,
        boolean parsed, boolean partialContent) {
    int flags = Pattern.DOTALL | Pattern.UNICODE_CASE;
    if (!caseSensitive) {
        flags = flags | Pattern.CASE_INSENSITIVE;
    }/* ww  w .  ja  v a2s  .com*/
    for (Pair<String, String> pair : stripPairs) {
        List<Pair<Integer, Integer>> matches = new ArrayList<Pair<Integer, Integer>>();
        Pattern leftPattern = Pattern.compile(pair.getLeft(), flags);
        Matcher leftMatch = leftPattern.matcher(content);
        while (leftMatch.find()) {
            Pattern rightPattern = Pattern.compile(pair.getRight(), flags);
            Matcher rightMatch = rightPattern.matcher(content);
            if (rightMatch.find(leftMatch.end())) {
                if (inclusive) {
                    matches.add(new ImmutablePair<Integer, Integer>(leftMatch.start(), rightMatch.end()));
                } else {
                    matches.add(new ImmutablePair<Integer, Integer>(leftMatch.end(), rightMatch.start()));
                }
            } else {
                break;
            }
        }
        for (int i = matches.size() - 1; i >= 0; i--) {
            Pair<Integer, Integer> matchPair = matches.get(i);
            content.delete(matchPair.getLeft(), matchPair.getRight());
        }
    }
}

From source file:util.StripHTMLTags.java

/**
 * This strips any given complete pattern from the body.
 *
 * @StringBuffer the body to strip//from   ww w .j  a  v a 2  s  .  co  m
 * @String the pattern to apply
 * @return StringBuffer return the stripped body
 */
StringBuffer stripPattern(StringBuffer body, String pattern) {
    Pattern mypattern = Pattern.compile(pattern, Pattern.DOTALL);
    Matcher matcher = mypattern.matcher(body);
    while (matcher.find()) {
        body = body.replace(matcher.start(), matcher.end(), "");
    }
    return body;
}

From source file:org.apache.zeppelin.interpreter.Interpreter.java

protected String interpolate(String cmd, ResourcePool resourcePool) {
    Pattern zVariablePattern = Pattern.compile("([^{}]*)([{]+[^{}]*[}]+)(.*)", Pattern.DOTALL);
    StringBuilder sb = new StringBuilder();
    Matcher m;//from w w w  . ja  v a  2  s  .  c  o  m
    String st = cmd;
    while ((m = zVariablePattern.matcher(st)).matches()) {
        sb.append(m.group(1));
        String varPat = m.group(2);
        if (varPat.matches("[{][^{}]+[}]")) {
            // substitute {variable} only if 'variable' has a value ...
            Resource resource = resourcePool.get(varPat.substring(1, varPat.length() - 1));
            Object variableValue = resource == null ? null : resource.get();
            if (variableValue != null)
                sb.append(variableValue);
            else
                return cmd;
        } else if (varPat.matches("[{]{2}[^{}]+[}]{2}")) {
            // escape {{text}} ...
            sb.append("{").append(varPat.substring(2, varPat.length() - 2)).append("}");
        } else {
            // mismatched {{ }} or more than 2 braces ...
            return cmd;
        }
        st = m.group(3);
    }
    sb.append(st);
    return sb.toString();
}

From source file:org.eclipse.rdf4j.repository.sparql.query.SPARQLOperation.java

protected Set<String> getBindingNames() {
    if (bindings.size() == 0)
        return Collections.EMPTY_SET;
    Set<String> names = new HashSet<String>();
    String qry = operation;/*from w  ww  .  j  ava2s .c o  m*/
    int b = qry.indexOf('{');
    String select = qry.substring(0, b);
    for (String name : bindings.getBindingNames()) {
        String replacement = getReplacement(bindings.getValue(name));
        if (replacement != null) {
            String pattern = ".*[\\?\\$]" + name + "\\W.*";
            if (Pattern.compile(pattern, Pattern.MULTILINE | Pattern.DOTALL).matcher(select).matches()) {
                names.add(name);
            }
        }
    }
    return names;
}

From source file:specminers.referenceparser.javamop.Extractor.java

private String expandExtendedRegularExpression(String ere, File specificationFile)
        throws IOException, ParseException {
    String contents = FileUtils.readFileToString(specificationFile);

    MOPSpecFileExt spec = getJavaMOPSpec(specificationFile);

    String strEvents = spec.getSpecs().get(0).getEventStr();

    if (spec.getSpecs().get(0).getPropertiesAndHandlers().get(0).getProperty() instanceof FormulaExt) {
        FormulaExt fext = (FormulaExt) spec.getSpecs().get(0).getPropertiesAndHandlers().get(0).getProperty();
        String strFormula = fext.toString();
        System.out.println(strFormula);
    }/*from   w ww  .ja  va  2s  . com*/

    if (1 > 0) {
        return "";
    }
    ere = ere.trim();
    String componentsPattern = "\\(\\w+\\)|\\w+";
    Matcher m = Pattern.compile(componentsPattern).matcher(ere);

    String aspectJExpression = "((execution)|(call))";
    String aspectjAdvicePattern = aspectJExpression;

    while (m.lookingAt()) {

        String component = ere.substring(m.start(), m.end());
        String componentDefintionRegex = "\\t*(creation)?[\\s\\t]+(event)[\\s|\\t]+" + component
                + aspectjAdvicePattern + "\\{(.+)\\}"; // According to JavaMOP 4 syntax
        Pattern p = Pattern.compile(componentDefintionRegex, Pattern.DOTALL);
        Matcher definitionMatcher = p.matcher(contents);

        if (definitionMatcher.find()) {
            String definition = definitionMatcher.group(5) + definitionMatcher.group(6);
            return definition;
        }
    }

    return ere;
}

From source file:org.apache.hadoop.chukwa.util.Filter.java

public Filter(String listOfPatterns) throws PatternSyntaxException {
    compiledPatterns = new ArrayList<SearchRule>();
    //FIXME: could escape these
    String[] patterns = listOfPatterns.split(SEPARATOR);
    for (String p : patterns) {
        int equalsPos = p.indexOf('=');

        if (equalsPos < 0 || equalsPos > (p.length() - 2)) {
            throw new PatternSyntaxException("pattern must be of form targ=pattern", p, -1);
        }//from   w w w. j a va  2s  . c o  m

        String targ = p.substring(0, equalsPos);
        if (!targ.startsWith("tags.") && !ArrayUtils.contains(SEARCH_TARGS, targ)) {
            throw new PatternSyntaxException("pattern doesn't start with recognized search target", p, -1);
        }

        Pattern pat = Pattern.compile(p.substring(equalsPos + 1), Pattern.DOTALL);
        compiledPatterns.add(new SearchRule(pat, targ));
    }
}

From source file:com.quinsoft.zeidon.standardoe.WriteOiToPorStream.java

void writeToStream() {
    // Compile a regex that will search for special printable chars later on.
    Pattern specialChars = Pattern
            .compile(".*[\\n\\r" + PortableFileReader.STRING_STORED_AS_BLOB_REGEX + "]+.*", Pattern.DOTALL);

    // Since we use it a lot, create a local value.
    boolean writeIncremental = flags.contains(WriteOiFlags.INCREMENTAL);

    // Used to create the link statements at the end.
    int hierIndex = 0;

    // Initialize instance flags that we'll use during the write.
    for (EntityInstanceImpl ei : view.getObjectInstance().getEntities()) {
        ei.setWritten(false);/*from ww w  .j a  v  a2s .  com*/
        ei.setRecordOwner(false);
        ei.setHierIndex(-1);
    }

    long lastLinked = -1;

    String erDate = "0";
    String incremental = writeIncremental ? "1" : "0";
    String compressed = "0";
    String optimisticOIs = "0";
    String attribFlags = writeIncremental ? "1" : "0";

    String name = view.getLodDef().getName();
    if (writer instanceof FileWriter)
        name = options.getResourceName();

    String header = String.format("z%s%s%s%s%sZeidon    %8s %s %s", erDate, incremental, compressed,
            optimisticOIs, attribFlags, name, view.getLodDef().getName().toUpperCase(),
            DATE_FORMATTER.print(new DateTime()));
    try {
        writeln(header);

        if (writeIncremental) {
            long flags = 0;
            if (view.getObjectInstance().isLocked())
                flags |= META_OI_LOCKED;

            if (view.getObjectInstance().isReadOnly())
                flags |= META_OI_READONLY;

            writeln("mOIFLAGS    %x", flags);
        }

        // Loop through the entities.  We can't use the iterator because the inner loop
        // object may skip some.
        for (EntityInstanceImpl ei = view.getObjectInstance().getRootEntityInstance(); ei != null; ei = ei
                .getNextHier()) {
            EntityDef entityDef = ei.getEntityDef();
            if (ei.isHidden() && !writeIncremental) {
                // EI is hidden and we're not writing incrementals, so skip this one
                // and all its children.
                ei = ei.getLastChildHier();
                continue;
            }

            ei.setHierIndex(hierIndex++);

            // Write out entity name and instance flags.
            write("e%-9s %d", entityDef.getName(), ei.getDepth());
            if (writeIncremental) {
                // Write the incremental flags.
                write(",%d", ei.getInstanceFlags());
            }
            writeln();

            if (flags.contains(WriteOiFlags.ENTITY_TAGS) || ei.getTag() != null) {
                String tag = ei.getTag();
                if (StringUtils.isBlank(tag))
                    tag = Integer.toHexString(ei.hashCode());
                writeln("mETAG      %s", tag);
            }

            if (flags.contains(WriteOiFlags.ENTITY_KEYS)) {
                writeln("mEKEY      %d", ei.getEntityKey());
            }

            // If the EI has already been written (this means it's linked to another
            // EI that has already been written) and it has no non-persist record,
            // then we don't need to write it's attribute values.
            if (ei.isWritten()) {
                lastLinked = ei.getHierIndex();
                ei.setWritten(true);
            } else {
                // The ei is linked and it hasn't been written so it must be the record
                // owner.
                ei.setRecordOwner(true);

                // Set the written flag for all the linked instances that belong
                // to this OI.
                for (EntityInstanceImpl linked : ei.getAllLinkedInstances()) {
                    if (linked.getObjectInstance() == view.getObjectInstance())
                        linked.setWritten(true);
                }
            }

            // Loops through all non-null attributes.
            for (AttributeDef AttributeDef : ei.getNonNullAttributeList()) {
                // Don't bother if the attribute is derived.
                if (AttributeDef.isDerived())
                    continue;

                if (flags.contains(WriteOiFlags.KEYS_ONLY) && !AttributeDef.isKey())
                    continue;

                // If this entity is the one that was most recently flagged as linked, don't
                // write persistent attributes -- they were already written for a linked
                // instance.
                if (AttributeDef.isPersistent() && ei.getHierIndex() == lastLinked)
                    continue;

                // Write the attribute flags if they aren't 0.
                String flags = "";
                if (writeIncremental && ei.getInternalAttribute(AttributeDef).getAttributeFlags() != 0)
                    flags = String.format(",%x", ei.getInternalAttribute(AttributeDef).getAttributeFlags());

                write("a%-9s ", AttributeDef.getName() + flags);

                if (AttributeDef.getType() == InternalType.BLOB) {
                    Blob blob = (Blob) ei.getAttribute(AttributeDef).getValue();
                    byte[] bytes = blob.getBytes();
                    writeln("%d", bytes.length);
                    write(bytes.toString());
                } else {
                    String value = ei.getAttribute(AttributeDef).getString();

                    // If the attribute type is a string then check to see if it contains "special"
                    // characters that interfere with normal attribute values, like "\n".
                    if (AttributeDef.getType() == InternalType.STRING
                            && (value.length() > 254 || specialChars.matcher(value).matches())) {
                        writeln("%c%d", PortableFileReader.STRING_STORED_AS_BLOB, value.length());
                    }

                    writeln("%s", value);
                }
            } // for each attribute...

            // Write a blank line just to look pretty.
            writeln();

        } // for each entity instance...

        // If any intra-object linked instances were found, create
        // link records now.
        if (lastLinked > -1) {
            for (EntityInstanceImpl ei : view.getObjectInstance().getEntities()) {
                // If we've gone past the last linked EI we're done.
                if (ei.getHierIndex() > lastLinked)
                    break;

                // If index is -1 it wasn't written.
                if (ei.getHierIndex() == -1)
                    continue;

                // If the entity is the record owner then we don't write link cards.
                // Link records are written for the non-record owner.
                if (ei.isRecordOwner())
                    continue;

                synchronized (ei.getAllLinkedInstances()) {
                    for (EntityInstanceImpl linked : ei.getAllLinkedInstances()) {
                        if (linked == ei)
                            continue; // Don't write a link record for ourself.

                        if (linked.getObjectInstance() == view.getObjectInstance() && linked.isRecordOwner()) {
                            assert ei.getHierIndex() != linked.getHierIndex() : "Mismatched record owners.";
                            assert ei.getEntityDef().getErEntityToken() == linked.getEntityDef()
                                    .getErEntityToken() : "Mismatched entity tokens";

                            writeln("i%-9d %d", ei.getHierIndex(), linked.getHierIndex());
                            break;
                        }
                    }
                }
            } // for each entity instance...
        } // if ( lastLinked > -1 )...

        // Indicate that the OI is done.
        writeln("ZEND");
    } catch (Throwable e) {
        throw ZeidonException.wrapException(e);
    }
}

From source file:com.ebay.jetstream.event.processor.esper.EPL.java

/**
 * Parses a single String containing a semicolon delimited list of EPL statements.
 *
 * @param statementBlock// w w w.  j  a  v  a2 s  .co  m
 *          the String containing all statements, with each statement separated by a semicolon.
 */

public void setStatementBlock(String statementBlock) {
    // TODO: better stmt delimiter parsing (e.g. skip ';' in a string or comment)
    m_statements.clear();
    m_statementsWithComments.clear();
    String noncomment = "";

    /**
     * This pattern removes statements with comments. 
     */
    if (statementBlock.contains("/*")) {
        Pattern p = Pattern.compile("/\\*(.*?)\\*/", Pattern.MULTILINE | Pattern.DOTALL);
        Matcher m = p.matcher(statementBlock);
        while (m.find()) {
            noncomment = m.replaceAll("");
        }
    } else {
        noncomment = statementBlock;
    }

    String pattern = "(?s);(?=(?:(?:.*?(?<!\\\\)\"){2})*[^\"]*$)(?=(?:(?:.*?(?<!\\\\)'){2})*[^']*$)";
    String[] stmts = noncomment.split(pattern, -1);
    for (String statement : stmts) {
        String trimmed = statement.trim();
        if (trimmed.length() > 0) {
            m_statements.add(trimmed);
        }
    }
}

From source file:com.cisco.gerrit.plugins.slack.message.PatchSetCreatedMessageGenerator.java

@Override
public boolean shouldPublish() {
    if (!config.isEnabled() || !config.shouldPublishOnPatchSetCreated()) {
        return false;
    }// w  w w.  j  a  v a 2s .c o  m

    // Ignore rebases or no code changes
    try {
        if (config.getIgnoreUnchangedPatchSet() && unchangedChangeKind(event.patchSet.get().kind)) {
            return false;
        }
    } catch (Exception e) {
        LOGGER.warn("Error checking patch set kind", e);
    }

    try {
        ChangeAttribute change;
        change = event.change.get();
        if (config.getIgnorePrivatePatchSet() && Boolean.TRUE.equals(change.isPrivate)) {
            return false;
        }
        if (config.getIgnoreWorkInProgressPatchSet() && Boolean.TRUE.equals(change.wip)) {
            return false;
        }
    } catch (Exception e) {
        LOGGER.warn("Error checking private and work-in-progress status", e);
    }

    boolean result;
    result = true;

    try {
        Pattern pattern;
        pattern = Pattern.compile(config.getIgnore(), Pattern.DOTALL);

        Matcher matcher;
        matcher = pattern.matcher(event.change.get().commitMessage);

        // If the ignore pattern matches, publishing should not happen
        result = !matcher.matches();
    } catch (Exception e) {
        LOGGER.warn("The specified ignore pattern was invalid", e);
    }

    return result;
}

From source file:com.clustercontrol.monitor.run.factory.RunMonitorStringValueType.java

/**
 * ????/* ww w. j a  va  2s  . c  om*/
 * <p>
 * ???????????
 * ???????????????????
 * 
 * @see com.clustercontrol.monitor.run.ejb.entity.MonitorStringValueInfoBean#getOrder_no()
 * @see com.clustercontrol.monitor.run.bean.MonitorStringValueInfo
 */
@Override
public int getCheckResult(boolean ret) {

    // -1 = ?-2 = ?????
    int result = -2;

    // ??
    if (!ret) {
        result = -1;
        return result;
    }

    // ???
    Pattern pattern = null;
    Matcher matcher = null;

    int orderNo = 0;
    // ??
    for (MonitorJudgementInfo info : m_judgementInfoList.values()) {

        ++orderNo;
        if (m_log.isDebugEnabled()) {
            m_log.debug("getCheckResult() value = " + m_value + ", monitorId = " + info.getMonitorId()
                    + ", orderNo = " + orderNo + ", pattern = " + info.getPattern());
        }

        // ?????
        if (info != null && info.getValidFlg()) {
            try {
                String patternText = info.getPattern();

                // ?????
                if (info.getCaseSensitivityFlg()) {
                    pattern = Pattern.compile(patternText, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
                }
                // ???
                else {
                    pattern = Pattern.compile(patternText, Pattern.DOTALL);
                }
                if (m_value == null) {
                    m_log.debug("getCheckResult(): monitorId=" + info.getMonitorId() + ", facilityId="
                            + m_facilityId + ", value=null");
                    result = -1;
                    return result;
                }
                matcher = pattern.matcher(m_value);

                // ????
                if (matcher.matches()) {
                    result = orderNo;

                    m_log.debug("getCheckResult() true : description=" + info.getDescription() + ", value="
                            + m_value);
                    m_log.debug("getCheckResult() true : message=" + info.getMessage());

                    break;
                }
            } catch (PatternSyntaxException e) {
                m_log.info("getCheckResult(): PatternSyntax is not valid." + " description="
                        + info.getDescription() + ", patternSyntax=" + info.getPattern() + ", value=" + m_value
                        + " : " + e.getClass().getSimpleName() + ", " + e.getMessage());
                result = -1;
            } catch (Exception e) {
                m_log.warn("getCheckResult(): PatternSyntax is not valid." + " description="
                        + info.getDescription() + ", patternSyntax=" + info.getPattern() + ", value=" + m_value
                        + " : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
                result = -1;
            }
        }
    }
    return result;
}