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.yahoo.flowetl.core.util.RegexUtil.java

/**
 * Gets the pattern for the given string by providing the rules to do
 * extraction.//from  w ww. j a  v  a  2 s  .  c  o m
 * 
 * This is similar to how php does regex to match you provide in the format
 * /REGEX/options where options currently are "i" for case insensitive and
 * "u" for unicode and "m" for multiline and "s" for dotall and the value
 * inside the // is the regex to use
 * 
 * @param str
 *            the string to parsed the pattern out of
 * 
 * @param cache
 *            whether to cache the compiled pattern
 * 
 * @return the pattern
 * 
 * @throws PatternSyntaxException
 * 
 *             the pattern syntax exception if it has wrong syntax
 */
public static Pattern getPattern(String str, boolean cache) throws PatternSyntaxException {
    if (str == null) {
        return null;
    }
    // see if we made it before...
    Pattern p = compiledPats.get(str);
    if (p != null) {
        return p;
    }
    Matcher mat = patExtractor.matcher(str);
    if (mat.matches() == false) {
        throw new PatternSyntaxException("Invalid syntax provided", str, -1);
    }
    String regex = mat.group(1);
    String opts = mat.group(2);
    int optsVal = 0;
    if (StringUtils.contains(opts, "i")) {
        optsVal |= Pattern.CASE_INSENSITIVE;
    }
    if (StringUtils.contains(opts, "u")) {
        optsVal |= Pattern.UNICODE_CASE;
    }
    if (StringUtils.contains(opts, "m")) {
        optsVal |= Pattern.MULTILINE;
    }
    if (StringUtils.contains(opts, "s")) {
        optsVal |= Pattern.DOTALL;
    }
    // compile and store it
    p = Pattern.compile(regex, optsVal);
    if (cache) {
        compiledPats.put(str, p);
    }
    return p;
}

From source file:com.palantir.docker.compose.matchers.IOMatchers.java

public static Matcher<String> matchingPattern(String patternStr) {
    return new TypeSafeDiagnosingMatcher<String>() {
        @Override//from  ww  w  .j  a  v a2 s.  c o  m
        protected boolean matchesSafely(String text, Description mismatchDescription) {
            Pattern pattern = Pattern.compile(patternStr, Pattern.DOTALL);
            boolean matches = pattern.matcher(text).matches();
            if (!matches) {
                mismatchDescription.appendText(text);
            }
            return matches;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("matching '" + patternStr + "'");
        }
    };
}

From source file:jGPIO.DTO.java

/**
 * @param args//from   w w  w.  ja v a  2 s . co m
 */
public DTO() {
    // determine the OS Version
    try {
        FileReader procVersion = new FileReader("/proc/version");

        char[] buffer = new char[100];
        procVersion.read(buffer);
        procVersion.close();
        String fullVersion = new String(buffer);

        String re1 = "(Linux)"; // Word 1
        String re2 = "( )"; // Any Single Character 1
        String re3 = "(version)"; // Word 2
        String re4 = "( )"; // Any Single Character 2
        String re5 = "(\\d+)"; // Integer Number 1
        String re6 = "(\\.)"; // Any Single Character 3
        String re7 = "(\\d+)"; // Integer Number 2
        String re8 = "(\\.)"; // Any Single Character 4
        String re9 = "(\\d+)"; // Integer Number 3

        Pattern p = Pattern.compile(re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8 + re9,
                Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher m = p.matcher(fullVersion);
        if (m.find()) {
            Integer linuxMajor = Integer.parseInt(m.group(5));
            Integer linuxMinor = Integer.parseInt(m.group(7));

            if (linuxMajor >= 3 && linuxMinor >= 8) {
                requireDTO = true;
            }
        }

    } catch (FileNotFoundException e) {
        System.out.println("Couldn't read the /proc/version. Please check for why it doesn't exist!\n");
        System.exit(1);
    } catch (IOException e) {
        System.out.println("Couldn't read in from /proc/version. Please cat it to ensure it is valid\n");
    }

    // no DTO generation required, so we'll exit and the customer can check
    // for requireDTO to be false
    if (!requireDTO) {
        System.out.println("No need for DTO");
        return;
    }
    // load the file containing the GPIO Definitions from the property file
    try {
        definitionFile = System.getProperty("gpio_definition");
        // No definition file, try an alternative name
        if (definitionFile == null) {
            System.getProperty("gpio_definitions");
        }
        if (definitionFile == null) {
            // Still no definition file, try to autodetect it.
            definitionFile = autoDetectSystemFile();
        }
        JSONParser parser = new JSONParser();
        System.out.println("Using GPIO Definitions file: " + definitionFile);
        pinDefinitions = (JSONArray) parser.parse(new FileReader(definitionFile));
    } catch (NullPointerException NPE) {
        System.out.println(
                "Could not read the property for gpio_definition, please set this since you are on Linux kernel 3.8 or above");
        System.exit(-1);
    } catch (FileNotFoundException e) {
        System.out.println("Could not read the GPIO Definitions file");
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(-1);
    }

}

From source file:ubic.gemma.web.feed.FeedReader.java

/**
 * @return List of news items in HTML format.
 *//*  w  w w  .j av a 2 s.co m*/
public List<NewsItem> getLatestNews() {

    /*
     * reformat the feed.
     */
    Pattern authorP = Pattern.compile("<p>.*?News Item.*?<b>(edited|added)</b>.*?by.*?<a.*?</p>",
            Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    Pattern footerP = Pattern.compile("<div style=.?padding: 10px 0;.*?View Online</a>.*?</div>",
            Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    Pattern borderP = Pattern.compile("border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;");
    List<NewsItem> result = new ArrayList<NewsItem>();
    try {
        SyndFeed feed = feedFetcher.retrieveFeed(new URL(feedUrl));

        for (SyndEntry k : (Collection<SyndEntry>) feed.getEntries()) {
            NewsItem n = new NewsItem();

            /*
             * This code is specific for confluence feeds.
             */
            String title = k.getTitle();

            String body = k.getDescription().getValue();
            Matcher m = authorP.matcher(body);
            body = m.replaceAll("");

            Matcher b = borderP.matcher(body);
            body = b.replaceAll("");

            /*
             * Confluence-specific
             */
            Matcher footerMatch = footerP.matcher(body);
            body = footerMatch.replaceAll("");

            n.setBody(body);
            n.setTitle(title);

            n.setDate(k.getPublishedDate());

            result.add(n);
        }
    } catch (Exception e) {
        NewsItem n = new NewsItem();
        n.setTitle("No news");
        n.setBody("");
    }
    return result;

}

From source file:org.sonar.java.checks.BadMethodName_S00100_Check.java

@Override
public void scanFile(JavaFileScannerContext context) {
    if (pattern == null) {
        pattern = Pattern.compile(format, Pattern.DOTALL);
    }/*ww  w .  j a v a 2 s .c o  m*/
    super.scanFile(context);
}

From source file:nz.net.orcon.kanban.automation.actions.RegexAction.java

public String extract(String text, String expressionString, int match, int group, String options)
        throws IOException {

    if (text == null) {
        text = "";
    }//  w w w. ja  v a  2s. c o  m

    if (expressionString == null) {
        throw new IllegalArgumentException(
                "No Regular Expression has been provided to carry out this operation.");
    }

    int optionsInEffect = 0;
    if (options != null) {
        for (String option : options.toUpperCase().split("\\|")) {
            optionsInEffect |= (option.equals("CANON_EQ")) ? Pattern.CANON_EQ
                    : (option.equals("CASE_INSENSITIVE")) ? Pattern.CASE_INSENSITIVE
                            : (option.equals("COMMENTS")) ? Pattern.COMMENTS
                                    : (option.equals("DOTALL")) ? Pattern.DOTALL
                                            : (option.equals("LITERAL")) ? Pattern.LITERAL
                                                    : (option.equals("MULTILINE")) ? Pattern.MULTILINE
                                                            : (option.equals("UNICODE_CASE"))
                                                                    ? Pattern.UNICODE_CASE
                                                                    : (option.equals("UNIX_LINES"))
                                                                            ? Pattern.UNIX_LINES
                                                                            : 0;
        }
    }

    Pattern expression = Pattern.compile(expressionString, optionsInEffect);
    Matcher matches = expression.matcher(text);

    int matchIndex = 1;
    while (matches.find()) {
        for (int groupIndex = 0; matches.groupCount() + 1 > groupIndex; groupIndex++) {
            if (matchIndex == match && groupIndex == group) {
                return matches.group(groupIndex);
            }
        }
        matchIndex++;
    }

    return "";
}

From source file:org.echocat.jomon.runtime.jaxb.PatternAdapter.java

@Nonnegative
protected int toFlags(@Nonnull String flagsAsString) {
    final Set<Character> flagsAsCharacters = newHashSet(toObject(flagsAsString.toCharArray()));
    int flags = 0;
    if (flagsAsCharacters.contains('i')) {
        flags |= Pattern.CASE_INSENSITIVE;
    }/*from  w  w w  .  j  av  a  2  s  .  c om*/
    if (flagsAsCharacters.contains('m')) {
        flags |= Pattern.MULTILINE;
    }
    if (flagsAsCharacters.contains('s')) {
        flags |= Pattern.DOTALL;
    }
    if (flagsAsCharacters.contains('x')) {
        flags |= Pattern.COMMENTS;
    }
    return flags;
}

From source file:org.rifidi.emulator.reader.thingmagic.commandobjects.FetchCommand.java

public FetchCommand(String command, ThingMagicReaderSharedResources tmsr) throws CommandCreationException {
    // TODO Auto-generated constructor stub
    this.command = command;
    this.tmsr = tmsr;

    this.tmsr = tmsr;
    this.command = command;

    List<String> tokens = new ArrayList<String>();
    /*//from w w  w .j  a  v  a  2  s . c o m
     * This regex looks for a Word, or a series of spaces on either side of
     * any single comparison operator or comma, or a single parentheses
     * (opening or closing). At the last ... any dangling spaces not
     * attached to the above groups and then anything else as a single
     * group.
     * 
     * This makes it really easy to parse the command string as it becomes
     * really predictable tokens.
     */
    Pattern tokenizer = Pattern.compile(
            // anything less...
            "[^\\s\\w,]+|" +
            // groups we are looking for...
                    "\\w+|" + "\\s*,\\s*|" + "\\s?+",
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher tokenFinder = tokenizer.matcher(command.toLowerCase().trim());

    while (tokenFinder.find()) {
        String temp = tokenFinder.group();
        /*
         * no need to add empty strings at tokens.
         */
        // TODO: Figure out why we are getting empty stings as tokens.
        if (temp.equals(""))
            continue;
        tokens.add(temp);
    }

    ListIterator<String> tokenIterator = tokens.listIterator();

    String token = tokenIterator.next();

    if (!token.equals("fetch"))
        throw new CommandCreationException("Error 0100:     syntax error at '" + token + "'");

    try {
        token = tokenIterator.next();

        if (!token.matches(WHITE_SPACE))
            throw new CommandCreationException("Error 0100:     syntax error at '" + token + "'");

        do {
            token = tokenIterator.next();
            if (!token.matches(A_WORD)) {
                throw new CommandCreationException("Error 0100:     syntax error at '" + token + "'");
            }

            if (!tmsr.getCursorCommandRegistry().containsKey(token)) {
                throw new CommandCreationException("Error 0100:   Cursor does not exist");
            }

            fetchList.add(token);

            if (!tokenIterator.hasNext()) {
                break;
            }

            token = tokenIterator.next();
            if (!token.matches(COMMA_WITH_WS)) {
                tokenIterator.previous();
                break;
            }

        } while (true);

        // check if the command correctly ends in a semicolon
        if (tokenIterator.hasNext()) {
            token = tokenIterator.next();

            if (token.matches(WHITE_SPACE)) {
                token = tokenIterator.next();
            }

            if (!token.equals(";")) {
                throw new CommandCreationException("Error 0100:     syntax error at '" + token + "'");
            }
        } else {
            throw new CommandCreationException("Error 0100:     syntax error at '\n'");
        }

    } catch (NoSuchElementException e) {
        /*
         * if we get here... we run out of tokens prematurely... Our job now
         * is to walk backwards to find the last non space tokens and throw
         * an exception saying that there is an syntax error at that point.
         */

        /*
         * look for the last offending command block that is not a series of
         * whitespaces.
         */

        token = tokenIterator.previous();
        while (token.matches(WHITE_SPACE)) {
            token = tokenIterator.previous();
        }
        logger.debug("Premature end of token list detected.");
        throw new CommandCreationException("Error 0100:     syntax error at '" + token + "'");

    }

}

From source file:de.rgielen.struts1.filter.ParamWrapperFilter.java

public void init(FilterConfig filterConfig) throws ServletException {
    final String toCompile;
    final String initParameter = filterConfig.getInitParameter(INIT_PARAM_NAME);
    if (initParameter != null && initParameter.trim().length() > 0) {
        toCompile = initParameter;//www. j ava2 s  .co m
    } else {
        toCompile = DEFAULT_BLACKLIST_PATTERN;
    }
    this.pattern = Pattern.compile(toCompile, Pattern.DOTALL);
}

From source file:io.wcm.maven.plugins.contentpackage.httpaction.PackageManagerHtmlMessageCall.java

@Override
public String execute() throws MojoExecutionException {
    if (log.isDebugEnabled()) {
        log.debug("Call URL: " + method.getURI());
    }//  www  .  j  a  v a2s .  c o  m

    try (CloseableHttpResponse response = httpClient.execute(method)) {
        String responseString = EntityUtils.toString(response.getEntity());

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

            // debug output whole xml
            if (log.isDebugEnabled()) {
                log.debug("CRX Package Manager Response:\n" + responseString);
            }

            // remove all HTML tags and special conctent
            final Pattern HTML_STYLE = Pattern.compile("<style[^<>]*>[^<>]*</style>",
                    Pattern.MULTILINE | Pattern.DOTALL);
            final Pattern HTML_JAVASCRIPT = Pattern.compile("<script[^<>]*>[^<>]*</script>",
                    Pattern.MULTILINE | Pattern.DOTALL);
            final Pattern HTML_ANYTAG = Pattern.compile("<[^<>]*>");

            responseString = HTML_STYLE.matcher(responseString).replaceAll("");
            responseString = HTML_JAVASCRIPT.matcher(responseString).replaceAll("");
            responseString = HTML_ANYTAG.matcher(responseString).replaceAll("");
            responseString = StringUtils.replace(responseString, "&nbsp;", " ");

            return responseString;
        } else {
            throw new MojoExecutionException("Failure:\n" + responseString);
        }

    } catch (IOException ex) {
        throw new MojoExecutionException("Http method failed.", ex);
    }
}