Example usage for java.util.regex Pattern MULTILINE

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

Introduction

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

Prototype

int MULTILINE

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

Click Source Link

Document

Enables multiline mode.

Usage

From source file:org.apache.asterix.test.aql.TestExecutor.java

public void runScriptAndCompareWithResultRegex(File scriptFile, File expectedFile, File actualFile)
        throws Exception {
    System.err.println("Expected results file: " + expectedFile.toString());
    String lineExpected, lineActual;
    int num = 1;//from   ww w  . j  a v a  2s. com
    try (BufferedReader readerExpected = new BufferedReader(
            new InputStreamReader(new FileInputStream(expectedFile), "UTF-8"));
            BufferedReader readerActual = new BufferedReader(
                    new InputStreamReader(new FileInputStream(actualFile), "UTF-8"))) {
        StringBuilder actual = new StringBuilder();
        while ((lineActual = readerActual.readLine()) != null) {
            actual.append(lineActual).append('\n');
        }
        while ((lineExpected = readerExpected.readLine()) != null) {
            if ("".equals(lineExpected.trim())) {
                continue;
            }
            Matcher m = REGEX_LINES_PATTERN.matcher(lineExpected);
            if (!m.matches()) {
                throw new IllegalArgumentException(
                        "Each line of regex file must conform to: [-]/regex/[flags]: " + expectedFile);
            }
            String negateStr = m.group(1);
            String expression = m.group(2);
            String flagStr = m.group(3);
            boolean negate = "-".equals(negateStr);
            int flags = Pattern.MULTILINE;
            if (flagStr.contains("m")) {
                flags |= Pattern.DOTALL;
            }
            if (flagStr.contains("i")) {
                flags |= Pattern.CASE_INSENSITIVE;
            }
            Pattern linePattern = Pattern.compile(expression, flags);
            boolean match = linePattern.matcher(actual).find();
            if (match && !negate || negate && !match) {
                continue;
            }
            throw new Exception("Result for " + scriptFile + ": expected pattern '" + expression
                    + "' not found in result.");
        }
    } catch (Exception e) {
        System.err.println("Actual results file: " + actualFile.toString());
        throw e;
    }

}

From source file:com.avapira.bobroreader.hanabira.HanabiraParser.java

@SuppressWarnings("ConstantConditions")
private void replaceAll(String begin, String end, SpanObjectFactory factory, int flag) {
    int removedFormatCharsDelta = 0;
    Pattern pattern = Pattern.compile(String.format("(%s)(.+?)(%s)", begin, end), Pattern.MULTILINE | flag);
    String beginRestore = restoreBreaks(begin);
    String endRestore = restoreBreaks(end);
    Matcher matcher = pattern.matcher(builder);
    String inlinedString;//www .  j av  a2s.c om

    boolean code = begin.contains("`");
    while (matcher.find()) {
        int start = matcher.start(2);
        int finish = matcher.end(2);

        // don't reformat in code blocks
        if (!code) {
            CodeBlockSpan[] spans = builder.getSpans(start, finish, CodeBlockSpan.class);
            if (spans != null && spans.length != 0) {
                continue;
            }
        }

        // don't reformat double borders while searchin for sinlges
        // e.g.: searching for "*abc*", found "**"
        inlinedString = matcher.group(2);
        if (inlinedString == null || "".equals(inlinedString)) {
            System.out.println(matcher.group());
            continue;
        }

        int lengthPrefix = matcher.group(1).length();
        builder.replace(matcher.start(1) - removedFormatCharsDelta, matcher.end(1) - removedFormatCharsDelta,
                beginRestore);

        builder.replace(matcher.start(3) - lengthPrefix - removedFormatCharsDelta + beginRestore.length(),
                matcher.end(3) - lengthPrefix - removedFormatCharsDelta + beginRestore.length(), endRestore);

        SpannableString rep = new SpannableString(matcher.group(2));
        rep.setSpan(factory.getSpan(), 0, rep.length(), 0);
        if (!code) {
            Linkify.addLinks(rep, Linkify.WEB_URLS);
            // fixme twice used Linkify? try remove and just setSpan to builder
        }
        builder.replace(matcher.start() - removedFormatCharsDelta + beginRestore.length(),
                matcher.start() + rep.length() - removedFormatCharsDelta + endRestore.length(), rep);

        // store deletions
        removedFormatCharsDelta += matcher.group(1).length() - beginRestore.length();
        removedFormatCharsDelta += matcher.group(3).length() - endRestore.length();
    }
}

From source file:org.silverpeas.components.kmelia.export.ODTDocumentBuilder.java

private void buildWithXMLText(final KmeliaPublication publication, final TextDocument odtDocument)
        throws Exception {
    boolean removeSection = true;
    String templateId = publication.getDetail().getInfoId();
    if (!isInteger(templateId)) {
        PublicationTemplate template = PublicationTemplateManager.getInstance()
                .getPublicationTemplate(publication.getPk().getInstanceId() + ":" + templateId);
        Form viewForm = template.getViewForm();
        RecordSet recordSet = template.getRecordSet();
        DataRecord dataRecord = recordSet.getRecord(publication.getPk().getId(), getLanguage());
        if (dataRecord == null) {
            dataRecord = recordSet.getEmptyRecord();
            dataRecord.setId(publication.getPk().getId());
        }//from  w w w  . ja v  a  2s.c  om
        PagesContext context = new PagesContext();
        context.setRenderingContext(RenderingContext.EXPORT);
        context.setLanguage(getLanguage());
        context.setComponentId(publication.getPk().getInstanceId());
        context.setObjectId(publication.getPk().getId());
        context.setBorderPrinted(false);
        context.setContentLanguage(getLanguage());
        context.setUserId(getUser().getId());
        context.setNodeId(getTopicIdOf(publication));
        String htmlText = viewForm.toString(context, dataRecord);
        if (isDefined(htmlText)) {
            //Suppress script tag
            htmlText = Pattern
                    .compile("<script[^>]*>.*?</script>",
                            Pattern.MULTILINE | Pattern.CASE_INSENSITIVE | Pattern.DOTALL)
                    .matcher(htmlText).replaceAll("");
            buildWithHTMLText(htmlText, in(odtDocument));
            removeSection = false;
        }
    }
    if (removeSection) {
        Section contentSection = odtDocument.getSectionByName(SECTION_CONTENT);
        contentSection.remove();
    }
}

From source file:com.github.rwitzel.streamflyer.regex.RegexModifierTest.java

@Test
public void testRemovalAtTheEndOfLine_usingMultiLineFlag() throws Exception {

    String endlessAbc = StringUtils.repeat("abc", 10000);

    String regex = "abc$";
    int flags = Pattern.MULTILINE;
    String replacement = "";
    String input = endlessAbc + "abc\n" + endlessAbc + "abc\n" + endlessAbc + "abc";
    String expectedOutput = endlessAbc + "\n" + endlessAbc + "\n" + endlessAbc;
    int lookBehind = 0;
    int capacityCharBuf = 3;

    assertReplacement(input, regex, replacement, lookBehind, capacityCharBuf, expectedOutput, flags);
}

From source file:org.opennms.netmgt.collectd.HttpCollector.java

private static List<HttpCollectionAttribute> processResponse(final Locale responseLocale,
        final String responseBodyAsString, final HttpCollectionSet collectionSet,
        HttpCollectionResource collectionResource) {
    LOG.debug("processResponse:");
    LOG.debug("responseBody = {}", responseBodyAsString);
    LOG.debug("getmatches = {}", collectionSet.getUriDef().getUrl().getMatches());
    List<HttpCollectionAttribute> butes = new LinkedList<HttpCollectionAttribute>();
    int flags = 0;
    if (collectionSet.getUriDef().getUrl().getCanonicalEquivalence()) {
        flags |= Pattern.CANON_EQ;
    }/*from   w  ww  . ja v  a  2 s.c  om*/
    if (collectionSet.getUriDef().getUrl().getCaseInsensitive()) {
        flags |= Pattern.CASE_INSENSITIVE;
    }
    if (collectionSet.getUriDef().getUrl().getComments()) {
        flags |= Pattern.COMMENTS;
    }
    if (collectionSet.getUriDef().getUrl().getDotall()) {
        flags |= Pattern.DOTALL;
    }
    if (collectionSet.getUriDef().getUrl().getLiteral()) {
        flags |= Pattern.LITERAL;
    }
    if (collectionSet.getUriDef().getUrl().getMultiline()) {
        flags |= Pattern.MULTILINE;
    }
    if (collectionSet.getUriDef().getUrl().getUnicodeCase()) {
        flags |= Pattern.UNICODE_CASE;
    }
    if (collectionSet.getUriDef().getUrl().getUnixLines()) {
        flags |= Pattern.UNIX_LINES;
    }
    LOG.debug("flags = {}", flags);
    Pattern p = Pattern.compile(collectionSet.getUriDef().getUrl().getMatches(), flags);
    Matcher m = p.matcher(responseBodyAsString);

    final boolean matches = m.matches();
    if (matches) {
        LOG.debug("processResponse: found matching attributes: {}", matches);
        final List<Attrib> attribDefs = collectionSet.getUriDef().getAttributes().getAttribCollection();
        final AttributeGroupType groupType = new AttributeGroupType(collectionSet.getUriDef().getName(),
                AttributeGroupType.IF_TYPE_ALL);

        final List<Locale> locales = new ArrayList<Locale>();
        if (responseLocale != null) {
            locales.add(responseLocale);
        }
        locales.add(Locale.getDefault());
        if (Locale.getDefault() != Locale.ENGLISH) {
            locales.add(Locale.ENGLISH);
        }

        for (final Attrib attribDef : attribDefs) {
            final String type = attribDef.getType();
            String value = null;
            try {
                value = m.group(attribDef.getMatchGroup());
            } catch (final IndexOutOfBoundsException e) {
                LOG.error(
                        "IndexOutOfBoundsException thrown while trying to find regex group, your regex does not contain the following group index: {}",
                        attribDef.getMatchGroup());
                LOG.error("Regex statement: {}", collectionSet.getUriDef().getUrl().getMatches());
                continue;
            }

            if (!type.matches("^([Oo](ctet|CTET)[Ss](tring|TRING))|([Ss](tring|TRING))$")) {
                Number num = null;
                for (final Locale locale : locales) {
                    try {
                        num = NumberFormat.getNumberInstance(locale).parse(value);
                        LOG.debug("processResponse: found a parsable number with locale \"{}\".", locale);
                        break;
                    } catch (final ParseException e) {
                        LOG.warn(
                                "attribute {} failed to match a parsable number with locale \"{}\"! Matched \"{}\" instead.",
                                attribDef.getAlias(), locale, value);
                    }
                }

                if (num == null) {
                    LOG.warn("processResponse: gave up attempting to parse numeric value, skipping group {}",
                            attribDef.getMatchGroup());
                    continue;
                }

                final HttpCollectionAttribute bute = new HttpCollectionAttribute(collectionResource,
                        new HttpCollectionAttributeType(attribDef, groupType), num);
                LOG.debug("processResponse: adding found numeric attribute: {}", bute);
                butes.add(bute);
            } else {
                HttpCollectionAttribute bute = new HttpCollectionAttribute(collectionResource,
                        new HttpCollectionAttributeType(attribDef, groupType), value);
                LOG.debug("processResponse: adding found string attribute: {}", bute);
                butes.add(bute);
            }
        }
    } else {
        LOG.debug("processResponse: found matching attributes: {}", matches);
    }
    return butes;
}

From source file:de.javakaffee.kryoserializers.KryoTest.java

@Test(enabled = true)
public void testRegex() throws Exception {
    final Holder<Pattern> pattern = new Holder<Pattern>(Pattern.compile("regex"));
    @SuppressWarnings("unchecked")
    final Holder<Pattern> deserialized = deserialize(serialize(pattern), Holder.class);
    assertDeepEquals(deserialized, pattern);

    final Holder<Pattern> patternWithFlags = new Holder<Pattern>(
            Pattern.compile("\n", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE));
    @SuppressWarnings("unchecked")
    final Holder<Pattern> deserializedWithFlags = deserialize(serialize(patternWithFlags), Holder.class);
    assertDeepEquals(deserializedWithFlags, patternWithFlags);
}

From source file:com.adgear.data.plugin.IDLSchemaMojo.java

/**
 * Factory method for generating instances of IDLObject
 *
 * @param name   File name/*from   ww w.  j a v a2 s .c  om*/
 * @param source IDL source code
 */
protected IDLObject generateIdlObject(String name, String source) {
    getLog().debug("Preprocessing file " + name);
    String namespaceAnnotationRegex = "(?<!\\w)@namespace\\(\"[a-zA-Z0-9$_\\.]+\"\\)";
    Matcher m = Pattern.compile(namespaceAnnotationRegex, Pattern.MULTILINE).matcher(source);
    while (m.find()) {
        getLog().warn("Ignoring @namespace annotation '" + m.group(1) + "'");
        source = m.replaceFirst(" ");
    }
    String namespace = name.replaceFirst("\\.[^\\.]+$", "");
    return new IDLObject(name, "@namespace(\"" + namespace + "\")\n" + source.trim(),
            collectDependencies(source));
}

From source file:org.apache.asterix.test.common.TestExecutor.java

public void runScriptAndCompareWithResultRegex(File scriptFile, File expectedFile, File actualFile)
        throws Exception {
    System.err.println("Expected results file: " + expectedFile.toString());
    String lineExpected, lineActual;
    try (BufferedReader readerExpected = new BufferedReader(
            new InputStreamReader(new FileInputStream(expectedFile), "UTF-8"));
            BufferedReader readerActual = new BufferedReader(
                    new InputStreamReader(new FileInputStream(actualFile), "UTF-8"))) {
        StringBuilder actual = new StringBuilder();
        while ((lineActual = readerActual.readLine()) != null) {
            actual.append(lineActual).append('\n');
        }// www  .ja va  2 s .  c o m
        while ((lineExpected = readerExpected.readLine()) != null) {
            if ("".equals(lineExpected.trim())) {
                continue;
            }
            Matcher m = REGEX_LINES_PATTERN.matcher(lineExpected);
            if (!m.matches()) {
                throw new IllegalArgumentException(
                        "Each line of regex file must conform to: [-]/regex/[flags]: " + expectedFile);
            }
            String negateStr = m.group(1);
            String expression = m.group(2);
            String flagStr = m.group(3);
            boolean negate = "-".equals(negateStr);
            int flags = Pattern.MULTILINE;
            if (flagStr.contains("m")) {
                flags |= Pattern.DOTALL;
            }
            if (flagStr.contains("i")) {
                flags |= Pattern.CASE_INSENSITIVE;
            }
            Pattern linePattern = Pattern.compile(expression, flags);
            boolean match = linePattern.matcher(actual).find();
            if (match && !negate || negate && !match) {
                continue;
            }
            throw new Exception("Result for " + scriptFile + ": expected pattern '" + expression
                    + "' not found in result.");
        }
    } catch (Exception e) {
        System.err.println("Actual results file: " + actualFile.toString());
        throw e;
    }

}

From source file:org.jenkinsci.plugins.workflow.support.steps.ExecutorStepTest.java

@Test
public void acquireWorkspace() throws Exception {
    story.addStep(new Statement() {
        @Override/*from  www  .  j  av  a 2  s  .c om*/
        public void evaluate() throws Throwable {
            @SuppressWarnings("deprecation")
            String slaveRoot = story.j.createTmpDir().getPath();
            story.j.jenkins.addNode(new DumbSlave("slave", "dummy", slaveRoot, "2", Node.Mode.NORMAL, "",
                    story.j.createComputerLauncher(null), RetentionStrategy.NOOP,
                    Collections.<NodeProperty<?>>emptyList()));
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "demo");
            p.setDefinition(new CpsFlowDefinition("node('slave') {\n" + // this locks the WS
            "    echo(/default=${pwd()}/)\n" + "    ws {\n" + // and this locks a second one
            "        echo(/before=${pwd()}/)\n" + "        semaphore 'wait'\n"
                    + "        echo(/after=${pwd()}/)\n" + "    }\n" + "}", true));
            p.save();
            WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
            SemaphoreStep.waitForStart("wait/1", b1);
            assertTrue(b1.isBuilding());
            WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
            SemaphoreStep.waitForStart("wait/2", b2);
            assertTrue(b2.isBuilding());
        }
    });
    story.addStep(new Statement() {
        void assertLogMatches(WorkflowRun build, String regexp) throws IOException { // TODO add to JenkinsRule
            String log = JenkinsRule.getLog(build);
            if (!Pattern.compile(regexp, Pattern.MULTILINE).matcher(log).find()) { // assertMatches present in some utility extension to JUnit/Hamcrest but not in our test CP
                fail(build + " log does not match /" + regexp + "/: " + log);
            }
        }

        @Override
        public void evaluate() throws Throwable {
            WorkflowJob p = (WorkflowJob) story.j.jenkins.getItem("demo");
            WorkflowRun b = p.getLastBuild();
            WorkflowRun b1 = p.getBuildByNumber(1);
            WorkflowRun b2 = p.getBuildByNumber(2);
            SemaphoreStep.success("wait/1", null);
            SemaphoreStep.success("wait/2", null);
            story.j.waitUntilNoActivity();
            story.j.assertBuildStatusSuccess(b1);
            story.j.assertBuildStatusSuccess(b2);
            assertLogMatches(b1, "^default=.+demo$");
            assertLogMatches(b1, "^before=.+demo@2$");
            assertLogMatches(b1, "^after=.+demo@2$");
            assertLogMatches(b2, "^default=.+demo@3$");
            assertLogMatches(b2, "^before=.+demo@4$");
            assertLogMatches(b2, "^after=.+demo@4$");
            SemaphoreStep.success("wait/3", null);
            WorkflowRun b3 = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
            assertLogMatches(b3, "^default=.+demo$");
            assertLogMatches(b3, "^before=.+demo@2$");
            assertLogMatches(b3, "^after=.+demo@2$");
        }
    });
}