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:com.ikanow.aleph2.enrichment.utils.services.SimpleRegexFilterService.java

/**
 * Converts a string of regex flags into a single int representing those
 * flags for using in the java Pattern object
 * //from w w w. ja v  a  2 s  .c om
 * @param flagsStr
 * @return
 */
public static int parseFlags(final String flagsStr) {
    int flags = 0;
    for (int i = 0; i < flagsStr.length(); ++i) {
        switch (flagsStr.charAt(i)) {
        case 'i':
            flags |= Pattern.CASE_INSENSITIVE;
            break;
        case 'x':
            flags |= Pattern.COMMENTS;
            break;
        case 's':
            flags |= Pattern.DOTALL;
            break;
        case 'm':
            flags |= Pattern.MULTILINE;
            break;
        case 'u':
            flags |= Pattern.UNICODE_CASE;
            break;
        case 'd':
            flags |= Pattern.UNIX_LINES;
            break;
        }
    }
    return flags;
}

From source file:org.wikipedia.citolytics.cpa.types.WikiDocument.java

/**
 * Extract headlines from article content.
 * <p/>//from  ww  w. j av  a  2  s .c  om
 * Wiki-Markup:
 * <p/>
 * ==Section==
 * ===Subsection===
 * ====Sub-subsection===
 *
 * @return List of headlines
 */
public List<String> getHeadlines() {
    List<String> headlines = new ArrayList<>();

    Pattern regex = Pattern.compile("^([=]{1,3})(.+)([=]{1,3})$", Pattern.MULTILINE);
    Matcher matcher = regex.matcher(raw);

    while (matcher.find()) {
        headlines.add(matcher.group(0).trim());
    }

    return headlines;
}

From source file:it.drwolf.ridire.utility.RIDIREPlainTextCleaner.java

private String substitute(String original, String regex, String subst) {
    Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
    Matcher m = p.matcher(original);
    return m.replaceAll(subst);
}

From source file:com.wavemaker.tools.project.LocalStudioConfiguration.java

/**
 * Gets the current VersionInfo from the VERSION file.
 *///from w  w  w. j a v  a 2 s. com
public static VersionInfo getCurrentVersionInfo() throws IOException {
    String versionFileString = getCurrentVersionInfoString();
    final Pattern p = Pattern.compile("^Version: (.*)$", Pattern.MULTILINE);
    Matcher m = p.matcher(versionFileString);
    if (!m.find()) {
        throw new WMRuntimeException("bad version string: " + versionFileString);
    }

    return new VersionInfo(m.group(1));
}

From source file:com.adobe.acs.commons.hc.impl.HealthCheckStatusEmailerTest.java

@Test
public void resultToPlainText() throws Exception {
    final List<HealthCheckExecutionResult> successResults = new ArrayList<>();
    successResults.add(successExecutionResult);
    final String actual = healthCheckStatusEmailer.resultToPlainText("HC Test", successResults);

    Matcher titleMatcher = Pattern.compile("^HC Test$", Pattern.MULTILINE).matcher(actual);
    Matcher entryMatcher = Pattern.compile("^\\[ OK \\]\\s+hc success$", Pattern.MULTILINE).matcher(actual);
    Matcher negativeMatcher = Pattern.compile("^\\[ CRTICAL \\]\\s+hc failure", Pattern.MULTILINE)
            .matcher(actual);/*from  w  w  w . j a  va2 s .  c o m*/

    assertTrue(titleMatcher.find());
    assertTrue(entryMatcher.find());
    assertFalse(negativeMatcher.find());
}

From source file:net.riezebos.thoth.configuration.persistence.ThothDB.java

private int determineCurrentVersion() throws IOException {
    int result = 0;
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(CREATE_SCRIPT);
    String script = ThothUtil.readInputStream(is);
    Pattern versionPattern = Pattern.compile("thoth_version.*values.*\\'thoth\\'\\,\\s*(\\d+)\\s*\\)",
            Pattern.MULTILINE);
    Matcher matcher = versionPattern.matcher(script);
    if (matcher.find()) {
        String group = matcher.group(1);
        result = Integer.parseInt(group);
    }/*  w ww .j a v  a  2s.  c o  m*/
    return result;
}

From source file:com.g3net.tool.StringUtils.java

/**
 * ?????/*from   ww  w  .j a v  a2 s  .  c  om*/
 * @param src ??
 * @param regex ???
 * @param ignoreCase ??
 * @param endPos src??(regex)??1
 * @return
 */
public static boolean startsWith(String src, String regex, boolean ignoreCase, TInteger endPos) {

    Pattern p = null;
    if (ignoreCase) {
        p = Pattern.compile("^" + regex, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    } else {
        p = Pattern.compile("^" + regex, Pattern.MULTILINE);
    }
    Matcher m = p.matcher(src);
    while (m.find()) {
        // log.info(m.group()+":"+m.start()+":"+m.end());
        endPos.setValue(m.end());
        return true;
    }
    return false;
}

From source file:com.etime.ETimeUtils.java

/**
 * Adds all Punches in a given string to a list of punches.
 *
 * @param row     The string to be searched for punches.
 * @param punches A list of punches to be added to.
 *///from w w  w . j av a  2s  .  c om
private static void addPunchesFromRowToList(String row, List<Punch> punches) {
    //Format to be matched is
    //  <td title="" class="InPunch"><div class="" title=""> 2:45PM </div></td>
    Pattern punchPattern = Pattern.compile("(?i)((InPunch|OutPunch)\">)(.*?)(>\\s*)(.*?)(\\s*</div>)",
            Pattern.MULTILINE | Pattern.DOTALL);
    Matcher punchMatcher = punchPattern.matcher(row);
    Punch punch;

    while (punchMatcher.find()) {
        String punchStr = punchMatcher.group(5);

        if (!punchStr.equals("&nbsp;")) {
            punch = getPunchFromString(punchStr);//parse a Punch from a string (e.g. "12:00PM")
            if (punchMatcher.group(2).equals("InPunch")) {
                punch.setClockIn(true);
            } else {
                punch.setClockIn(false);
            }
            punches.add(punch);
        }
    }
}

From source file:org.extensiblecatalog.ncip.v2.millennium.MillenniumLookupUserService.java

/**
 * Handles a NCIP LookupUser service by returning hard-coded data.
 * //from ww w.  jav a2 s .c  o  m
 * @param initData
 *            the LookupUserInitiationData
 * @param serviceManager
 *            provides access to remote services
 * @return LookupUserResponseData
 */
@Override
public LookupUserResponseData performService(LookupUserInitiationData initData,
        RemoteServiceManager serviceManager) {

    String baseUrl = "https://" + IIIClassicBaseUrl + "/patroninfo%7ES0/";

    final LookupUserResponseData responseData = new LookupUserResponseData();

    String userId = initData.getUserId().getUserIdentifierValue();

    MillenniumRemoteServiceManager millenniumSvcMgr = (MillenniumRemoteServiceManager) serviceManager;

    String strSessionId = millenniumSvcMgr.getIIISessionId(baseUrl);

    String redirectedUrl = millenniumSvcMgr.authenticate(authenticatedUserName, authenticatedUserPassword,
            baseUrl, strSessionId);

    // if the returned logIntoWebForm isn't null
    if (redirectedUrl != null) {
        // extract the iii id from the URL
        int start = redirectedUrl.indexOf("~S0/");

        // Check to see if we're not redirected to the "top"
        int end = redirectedUrl.indexOf("/top");
        if (end == -1) {
            end = redirectedUrl.indexOf("/items");
        }

        String urid = redirectedUrl.substring(start, end).replace("~S0/", "");

        authenticatedUserId = urid;
    }

    boolean getBlockOrTrap = false;
    boolean getAddress = true;
    boolean getVisibleUserID = true;
    boolean getFines = true;
    boolean getHolds = false;
    boolean getLoans = false;
    boolean getRecalls = false;
    boolean getMessages = false;

    // System.out.println("xcLookupUser authID: " + authenticatedUserId);
    // System.out.println("xcLookupUser redirUrl: " + redirectedUrl);

    // setup lookup method
    GetMethod lookupMethod = new GetMethod(redirectedUrl);
    lookupMethod.addRequestHeader("Cookie", "III_SESSION_ID=" + strSessionId);

    try {
        try {
            client.executeMethod(lookupMethod);
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String html = lookupMethod.getResponseBodyAsString();
        // log.error(html);

        /**
         * Boolean Values to Return as objects
         */

        // TODO xcLookupUser: Finish getBlockOrTrap
        // If getBlockOrTrap is true, the returned users list of blocks
        // must contain all blocks currently placed on the user represented
        // by the userId field.
        if (getBlockOrTrap) {
            // log.debug("Get Block or Trap");
            System.out.println("Todo: Get Block or Trap");
        }

        // TODO xcLookupUser: Finish getAddres (Temp Address) if possible
        // If getMessages is true, the returned users list of messages must
        // contain all messages applying the user represented by the userId

        if (getAddress) {
            // log.debug("Get Address");
            Pattern address = Pattern.compile(
                    "^<span(.*?)class=\"large\">(?s)(.*?)</form>(?s)(.*?)<p>(?s)(.*?)<br />(?s)(.*?)<p>(?s)(.*?)</span>$",
                    Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
            Matcher addressMatch = address.matcher(html);

            addressMatch.find();
            // System.out.println(addressMatch.group(5));

            String strAddress = addressMatch.group(5).replaceAll("<br />", "|").replaceAll("\\n", "")
                    .replaceAll("||", "");
            strAddress = strAddress.replace("||", "");

            // returnUser.setAddress(strAddress);
            System.out.println("Found the home address " + strAddress);
            // + " for the patron with patron ID " + patronId)
            // log.debug("Found the home address " + returnUser.getAddress()
            // + " for the patron with patron ID " + patronId);

        }

        // if true, the user's fullName must be set to the correct value for
        // the user represented by the userId field if this value is known.
        if (getVisibleUserID) {
            // log.debug("get Visible User Id");

            // If there were any results, build the full name string
            Pattern visibleId = Pattern.compile(
                    "^<span(.*?)class=\"large\">(?s)(.*?)</form>(?s)(.*?)<p>(?s)(.*?)<br />(?s)(.*?)<p>(?s)(.*?)</span>$",
                    Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
            Matcher visibleIdMatch = visibleId.matcher(html);

            visibleIdMatch.find();
            // System.out.println(visibleIdMatch.group(4));

            // Clean up strName, removing tags
            String strName = visibleIdMatch.group(4).replace("<strong>", "").replace("</strong>", "");

            // set full name to strName, removing any unneded whitespaces
            String fullName = strName.trim();

            // Check to make sure it exists
            if (fullName.length() > 1) {

                // setFullName(fullName);
                System.out.println(fullName);

                // log.debug("Found the user's full name to be "
                // + returnUser.getFullName());
            } else {
                // log
                // .info("Could not find the name information for the patron with patron ID "
                // + patronId);
            }

        }

        // TODO xcLookupUser: Finish getFines
        // if true the user's totalFinesCurrencyCode and totalFines fields
        // must be set to the correct values for the user represented by the
        // userId field if these values are known. In addition, the list of
        // fines must contain NCIPUserFine Objects for all fines the user
        // owes.
        if (getFines) {
            // log.debug("get Fines");
            // https://jasmine.uncc.edu/patroninfo~S0/1205433/overdues
            System.out.println("Get Fines");
            // System.out.println("Auth: " + authenticatedUserId);

            html = millenniumSvcMgr.getFines(authenticatedUserId, strSessionId);

            Pattern fines = Pattern.compile(
                    "^(?s)(.*?)<table(.*?)class=\"patFunc\">(?s)(.*?)</table>(?s)(.*?)$",
                    Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);

            Matcher finesMatch = fines.matcher(html);

            if (finesMatch.matches()) {

                finesTable = finesMatch.group(3).toString();

            }

            System.out.println(finesTable);

            System.out.println("==================");

            fines = Pattern.compile("^(?s)(.*?)<tr class=\"patFuncFinesEntryTitle\">(?s)(.*?)</tr>(?s)(.*?)$",
                    Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);

            finesMatch = fines.matcher(finesTable);

            Pattern title = Pattern.compile("^(?s)(.*?)<em>(?s)(.*?)</em></td>(?s)(.*?)$",
                    Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);

            while (finesMatch.find()) {

                //for (int i=0; i < finesMatch.groupCount(); i++) {

                System.out.println(finesMatch.group(2));

                Matcher titleMatch = title.matcher(finesMatch.group(2));
                // Grab the title out of the finesMatch string
                System.out.println("=====");

                if (titleMatch.matches()) {
                    System.out.println(titleMatch.group(2));
                }

                System.out.println("=====");

                //}

            }

            System.out.println("==================");

            /*
             * <table border="1" width="100%" class="patFunc"> <tbody>
             * 
             * </tbody> </table>
             */

            // TODO Parse out fines, and add them to objects

        }

        // TODO xcLookupUser: Finish getHolds
        // If getHolds is true, the returned users list of holds must
        // contain NCIPUserRequestedItem Objects for all holds and callslips
        // the user represented by the userId field has placed.
        if (getHolds) {
            System.out.println("Todo: get holds");

            /*
             * NCIPUserRequestedItem item = new
             * NCIPUserRequestedItem(results .getDate("date_hold_placed"),
             * // The date the request // was placed null, // The date the
             * request is expected to become // available newItem); // The
             * bibliographic ID of the item the // request is for
             * 
             * // Add the item to the list of requested items
             * returnUser.addRequestedItem(item);
             */
        }
        // If getLoans is true, the returned users list of checkedOutItems
        // must contain NCIPUserLoanedItem Objects for all items the user
        // represented by the userId field has checked out.
        if (getLoans) {
            System.out.println("get Loans");

            // Setup Request URL
            String requestUrl = redirectedUrl.substring(0, redirectedUrl.lastIndexOf("/")) + "/items";

            // setup getLoans method
            GetMethod getLoansMethod = new GetMethod(requestUrl);
            getLoansMethod.addRequestHeader("Cookie", "III_SESSION_ID=" + strSessionId);

            // Grab items page
            try {
                client.executeMethod(getLoansMethod);

                String loansHtml = getLoansMethod.getResponseBodyAsString();
                // Parse out the second page

                // System.out.println(loansHtml);

                // If there were any results, build the full name string
                Pattern loans = Pattern.compile(
                        "^(?s)(.*?)<table(.*?)class=\"patFunc\">(?s)(.*?)<th(.*?)>(?s)(.*?)</th>(?s)(.*?)</tr>(?s)(.*?)</table>(?s)(.*?)$",
                        Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);

                Matcher loansMatch = loans.matcher(loansHtml);

                if (loansMatch.matches()) {
                    // System.out.println("Matches");
                    // System.out.println(loansMatch.groupCount());

                    // for (int i=0; i < loansMatch.groupCount(); i++) {
                    // Add to String Buffer
                    // System.out.println(loansMatch.group(7));
                    // }
                    String loansTable = loansMatch.group(7).toString();
                    // loansTable = loansTable.replaceAll("\n\n","");

                    Pattern loansTwo = Pattern.compile(
                            "^(.*?)<tr(.*?)class=\"patFuncEntry\">(?s)(.*?)</tr>(?s)(.*?)$",
                            Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);

                    Matcher loansTwoMatch = loansTwo.matcher(loansTable);

                    // initialize variables
                    StringBuffer sb = new StringBuffer();
                    String lineMatch;
                    String strCleanup;

                    /*
                     * Pattern loansThree = Pattern.compile(
                     * "^(.*?)value=\"(.*?)\"(.*?)$",
                     * Pattern.CASE_INSENSITIVE);
                     */

                    // loop over each iteration
                    while (loansTwoMatch.find()) {

                        // Replacements to get pipe delmited output
                        lineMatch = loansTwoMatch.group(3).replaceAll("\n", "");

                        lineMatch = lineMatch.replaceAll(
                                "<td align=\"left\" class=\"patFuncMark\"><input type=\"checkbox\" name=\"renew(.*?)\" value=\"",
                                "");
                        lineMatch = lineMatch.replaceAll("\"(.*?)href=\"(.*?)&", "'|'");
                        lineMatch = lineMatch.replaceAll("</a>(.*?)Barcode\">", "'|'");
                        lineMatch = lineMatch.replaceAll("</td>(.*?)patFuncStatus\">", "'|'");
                        lineMatch = lineMatch.replaceAll("</td>(.*?)patFuncCallNo\">", "'|'");
                        lineMatch = lineMatch.replaceAll("\"> ", "'|'");
                        lineMatch = lineMatch.replaceAll(" </td>", "");

                        // Append Pipe delimited to string buffer
                        sb.append(lineMatch + "\n");

                    }
                    // Convert to string for output
                    strCleanup = sb.toString();

                    String aryTest[] = stringToArray(strCleanup, "\n");

                    // System.out.println(aryTest[1]);

                    // Loop Over Loans
                    for (int i = 0; i < aryTest.length; i++) {

                        // Split up, and turn into array / assign to object
                        String aryVal[] = aryTest[i].split("'|'");

                        /*
                         * This is all we can get, itemid, bib, title,
                         * barcode duedate and call number
                         * System.out.println("--" + i);
                         * System.out.print("| item: " + aryVal[0] +
                         * "| bib: b" + aryVal[2] + "| title " + aryVal[4] +
                         * "| barcode: " + aryVal[6] + "| due: " + aryVal[8]
                         * + "| CN: " + aryVal[10]);
                         * 
                         * System.out.println("--");
                         */

                        // set variables for loaned object
                        String strAgencyId = strConfig.getProperty("defaultAgency");/*
                                                                                    * configuration
                                                                                    * .getProperty(
                                                                                    * Constants.
                                                                                    * CONFIG_ILS_DEFAULT_AGENCY
                                                                                    * );
                                                                                    */

                        // Start Date Format
                        Date dateDue = null; // set to null
                        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT); // create
                        // formatter

                        String strDate = aryVal[8].replaceAll("DUE ", "").replace("-", "/"); // format string

                        // System.out.println(strDate); // for testing

                        // parse the date
                        try {
                            dateDue = dateFormatter.parse(strDate);
                        } catch (ParseException pe) {
                            System.out.println("LookupUser ERROR: Cannot parse \"" + strDate + "\"");
                        }

                        // add b to the value for the bib
                        String bibId = "b" + aryVal[2];

                        // Create a new item for each loaned item
                        /*
                         * NCIPUserLoanedItem item = new NCIPUserLoanedItem(
                         * dateDue, new NCIPItem(new NCIPAgency(
                         * strAgencyId), bibId));
                         */
                        // add object to returnUser
                        // returnUser.addLoanedItem(item);

                        System.out.println(
                                "Added the user's loaned item with item ID " + bibId + " Due: " + dateDue);

                    }

                } // end matches

                // Error handling
            } catch (HttpException e) {
                e.printStackTrace();
                /*
                 * throw new ILSException("HttpException thrown, exiting.",
                 * Constants.ERROR_INTERNAL_ERROR, new StrictNcipError(true,
                 * "NCIP General Processing Error",
                 * "Temporary Processing Failure", "NCIPMessage", null));
                 */
            } catch (IOException e) {
                e.printStackTrace();
                /*
                 * throw new ILSException("IOException thrown, exiting.",
                 * Constants.ERROR_INTERNAL_ERROR, new StrictNcipError(true,
                 * "NCIP General Processing Error",
                 * "Temporary Processing Failure", "NCIPMessage", null));
                 */
            }

        }

        // TODO xcLookupUser: Finish Recalls
        // If getRecalls is true, the returned users list of recalls must
        // contain XCUserRecalledItem Objects for all recalls the user
        // represented by the userId field has placed.
        if (getRecalls) {
            System.out.println("Todo: get Recalls");
        }

        // TODO xcLookupUser: Finish getMessages
        // If getMessages is true, the returned users list of messages must
        // contain all messages applying the user represented by the userId.
        if (getMessages) {
            System.out.println("Todo: get Messages");
        }

        // return returnUser;

    } catch (HttpException e) {
        e.printStackTrace();
        /*
         * throw new ILSException( "HttpException thrown, exiting.",
         * Constants.ERROR_INTERNAL_ERROR, new StrictNcipError(true,
         * "NCIP General Processing Error", "Temporary Processing Failure",
         * "NCIPMessage", null));
         */
    } catch (IOException e) {
        e.printStackTrace();
        /*
         * throw new ILSException( "IOException thrown, exiting.",
         * Constants.ERROR_INTERNAL_ERROR, new StrictNcipError(true,
         * "NCIP General Processing Error", "Temporary Processing Failure",
         * "NCIPMessage", null));
         */
    }

    user.setUserIdentifierValue(userId);
    responseData.setUserId(user);
    // Echo back the same item id that came in
    // responseData.setUserId(initData.getUserId());
    return responseData;
}

From source file:com.francetelecom.clara.cloud.logicalmodel.LogicalConfigServiceUtils.java

protected String escapesPoundsInComments(String rawComment) {
    return Pattern.compile("^[#!]", Pattern.MULTILINE).matcher(rawComment).replaceAll("");
}