List of usage examples for java.util.regex Matcher toMatchResult
public MatchResult toMatchResult()
From source file:Main.java
public static String url2Folder(String url) { Pattern p = Pattern.compile("android/(.*?)/"); Matcher m = p.matcher(url); if (m.find()) { MatchResult mr = m.toMatchResult(); return mr.group(1); } else {/*from w w w. ja v a 2s.c o m*/ return null; } }
From source file:Main.java
public static String extractPattern(String string, String pattern) { Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(string); if (!m.find()) return null; return m.toMatchResult().group(1); }
From source file:Main.java
private static String extractPattern(String string, String pattern) { Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(string); if (!m.find()) { return null; }/* w w w . j ava2s . c om*/ return m.toMatchResult().group(1); }
From source file:com.perl5.lang.perl.lexer.RegexBlock.java
/** * Parses guaranteed opened regex block//from w ww .j a v a 2s. com * * @param buffer Input characters stream * @param startOffset Start parsing offset * @param bufferEnd Buffer last offset * @param openingChar Opener character * @return Parsed regex block or null if failed */ public static RegexBlock parseBlock(CharSequence buffer, int startOffset, int bufferEnd, char openingChar, boolean isSecondBlock) { char closingChar = getQuoteCloseChar(openingChar); boolean isEscaped = false; boolean isCharGroup = false; boolean isQuotesDiffers = closingChar != openingChar; int braceLevel = 0; int parenLevel = 0; int delimiterLevel = 0; RegexBlock newBlock = null; int currentOffset = startOffset; while (true) { if (currentOffset >= bufferEnd) { break; } char currentChar = buffer.charAt(currentOffset); if (delimiterLevel == 0 && braceLevel == 0 && !isCharGroup && !isEscaped && parenLevel == 0 && closingChar == currentChar) { newBlock = new RegexBlock(buffer, startOffset, currentOffset + 1, openingChar, closingChar); break; } if (!isSecondBlock) { if (!isEscaped && !isCharGroup && currentChar == '[') { Matcher m = POSIX_CHAR_CLASS_PATTERN.matcher(buffer.subSequence(currentOffset, bufferEnd)); if (m.lookingAt()) { currentOffset += m.toMatchResult().group(0).length(); continue; } else { isCharGroup = true; } } else if (!isEscaped && isCharGroup && currentChar == ']') { isCharGroup = false; } // @todo this is buggy, sometimes bare is allowed. See example from `redo` doc // if (!isEscaped && !isCharGroup && currentChar == '{') // braceLevel++; // else if (!isEscaped && !isCharGroup && braceLevel > 0 && currentChar == '}') // braceLevel--; // // if (!isEscaped && !isCharGroup && currentChar == '(') // parenLevel++; // else if (!isEscaped && !isCharGroup && parenLevel > 0 && currentChar == ')') // parenLevel--; } if (!isEscaped && isQuotesDiffers && !isCharGroup) { if (currentChar == openingChar) { delimiterLevel++; } else if (currentChar == closingChar && delimiterLevel > 0) { delimiterLevel--; } } isEscaped = !isEscaped && closingChar != '\\' && currentChar == '\\'; currentOffset++; } return newBlock; }
From source file:net.solarnetwork.util.StringMerger.java
/** * Merge from a String source into a StringBuilder. * //from ww w .ja v a2s . co m * @param src * the source String to substitute into * @param data * the data object to substitute with * @param nullValue * the value to substitute for null data * @param buf * the StringBuilder to append the output to */ public static void mergeString(String src, Object data, String nullValue, StringBuilder buf) { Matcher matcher = MERGE_VAR_PAT.matcher(src); //MatchResult[] matches = MERGE_VAR_PAT.matcher(src); //REMatch[] matches = MERGE_VAR_RE.getAllMatches(src); if (!matcher.find()) { buf.append(src); } else { int endLastMatchIdx = 0; do { MatchResult matchResult = matcher.toMatchResult(); // append everything from the end of the last // match to the start of this match buf.append(src.substring(endLastMatchIdx, matchResult.start())); // perform substitution here... if (data != null) { int s = matchResult.start(1); int e = matchResult.end(1); if ((s > -1) && (e > -1)) { String varName = src.substring(s, e); if (data instanceof java.util.Map<?, ?>) { Object o = null; int sepIdx = varName.indexOf('.'); if (sepIdx > 0) { String varName2 = varName.substring(sepIdx + 1); varName = varName.substring(0, sepIdx); o = ((Map<?, ?>) data).get(varName); if (o != null) { try { o = PropertyUtils.getProperty(o, varName2); } catch (Exception e2) { LOG.warn("Exception getting property '" + varName2 + "' out of " + o.getClass() + ": " + e2); } } } else { // simply check for key o = ((Map<?, ?>) data).get(varName); } if (o == null || (String.class.isAssignableFrom(o.getClass()) && !StringUtils.hasText(o.toString()))) { buf.append(nullValue); } else { buf.append(o); } } else { // use reflection to get a bean property try { Object o = PropertyUtils.getProperty(data, varName); if (o == null || (String.class.isAssignableFrom(o.getClass()) && !StringUtils.hasText(o.toString()))) { buf.append(nullValue); } else { buf.append(o); } } catch (Exception ex) { LOG.warn("Exception getting property '" + varName + "' out of " + data.getClass() + ": " + ex); buf.append(nullValue); } } } endLastMatchIdx = matchResult.end(); } } while (matcher.find()); if (endLastMatchIdx < src.length()) { buf.append(src.substring(endLastMatchIdx)); } } }
From source file:gov.lanl.adore.djatoka.plugin.ExtractPDF.java
/** * Get PDF information with pdfinfo://from ww w . j ava 2s. c o m * - "Pages: X": number of pages; * - "Page X size: www.ww hhh.hh": size of each page, in pts. * @returns a map: * - [Pages][n] * - [Page 1][111.11 222.22] * - [Page i][www.ww hhh.hh] * - [Page n][999.99 1000.00] */ private static Map<String, String> getPDFProperties(ImageRecord input) throws DjatokaException { logger.debug("Getting PDF info"); try { setPDFCommandsPath(); } catch (IllegalStateException e) { logger.error("Failed to set PDF commands path: ", e); throw e; } HashMap<String, String> pdfProperties = new HashMap<String, String>(); String sourcePath = null; if (input.getImageFile() != null) { logger.debug("PDFInfo image file: " + input.getImageFile()); sourcePath = input.getImageFile(); } else if (input.getObject() != null && (input.getObject() instanceof InputStream)) { FileInputStream fis = null; fis = (FileInputStream) input.getObject(); File in; // Copy to tmp file try { String cacheDir = OpenURLJP2KService.getCacheDir(); if (cacheDir != null) { in = File.createTempFile("tmp", ".pdf", new File(cacheDir)); } else { in = File.createTempFile("tmp", ".pdf"); } in.deleteOnExit(); FileOutputStream fos = new FileOutputStream(in); IOUtils.copyStream(fis, fos); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } sourcePath = in.getAbsolutePath(); } else { throw new DjatokaException("File not defined and Input Object Type " + input //.getObject().getClass().getName() + " is not supported"); } String pdfinfoCmd[] = PDFINFO_COMMAND.clone(); pdfinfoCmd[PDFINFO_COMMAND_POSITION_BIN] = pdfinfoPath; pdfinfoCmd[PDFINFO_COMMAND_POSITION_FIRSTPAGE] = "1"; pdfinfoCmd[PDFINFO_COMMAND_POSITION_LASTPAGE] = "-1"; // Last page even we not knowing its number. pdfinfoCmd[PDFINFO_COMMAND_POSITION_FILE] = sourcePath; Process pdfProc = null; try { ArrayList<MatchResult> pageSizes = new ArrayList<MatchResult>(); MatchResult pages = null; pdfProc = Runtime.getRuntime().exec(pdfinfoCmd); BufferedReader lr = new BufferedReader(new InputStreamReader(pdfProc.getInputStream())); String line; for (line = lr.readLine(); line != null; line = lr.readLine()) { Matcher mm1 = PAGES_PATT.matcher(line); if (mm1.matches()) pages = mm1.toMatchResult(); Matcher mm2 = MEDIABOX_PATT.matcher(line); if (mm2.matches()) pageSizes.add(mm2.toMatchResult()); } int istatus = pdfProc.waitFor(); if (istatus != 0) logger.error("pdfinfo proc failed, exit status=" + istatus + ", file=" + sourcePath); if (pages == null) { logger.error("Did not find 'Pages' line in output of pdfinfo command: " + Arrays.deepToString(pdfinfoCmd)); pdfProperties.put("Pages", "0"); } else { //int n = Integer.parseInteger(pages.group(1)); pdfProperties.put("Pages", pages.group(1)); } if (pageSizes.isEmpty()) { logger.error("Did not find \"Page X size\" lines in output of pdfinfo command: " + Arrays.deepToString(pdfinfoCmd)); throw new IllegalArgumentException("Failed to get pages size of PDF with pdfinfo."); } else { for (MatchResult mr : pageSizes) { String page = mr.group(1); float x0 = Float.parseFloat(mr.group(2)); float y0 = Float.parseFloat(mr.group(3)); float x1 = Float.parseFloat(mr.group(4)); float y1 = Float.parseFloat(mr.group(5)); float w = Math.abs(x1 - x0); float h = Math.abs(y1 - y0); // Have to scale page sizes by max dpi (MAX_DPI / DEFAULT_DENSITY). Otherwise, BookReader.js will request the wrong zoom level (svc.level). float ws = w * MAX_DPI / DEFAULT_DENSITY; float hs = h * MAX_DPI / DEFAULT_DENSITY; String width = "" + ws; //mr.group(2); String height = "" + hs; //mr.group(3); pdfProperties.put("Page " + page, width + " " + height); } } } catch (Exception e) { logger.error("Failed getting PDF information: ", e); throw new DjatokaException("Failed getting PDF information: ", e); } finally { // Our exec() should just consume one of the streams, but we want to stay safe. // http://mark.koli.ch/2011/01/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec.html org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getOutputStream()); org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getInputStream()); org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getErrorStream()); } return pdfProperties; }
From source file:org.apache.hadoop.hive.ql.udf.UDFRegExpExtract.java
public String evaluate(String s, String regex, Integer extractIndex) { if (s == null || regex == null) { return null; }//from ww w .ja va 2 s.com if (!regex.equals(lastRegex) || p == null) { lastRegex = regex; p = Pattern.compile(regex); } Matcher m = p.matcher(s); if (m.find()) { MatchResult mr = m.toMatchResult(); return mr.group(extractIndex); } return ""; }
From source file:org.apache.flink.table.runtime.functions.SqlFunctionUtils.java
/** * Returns a string extracted with a specified regular expression and a regex * match group index./*from w w w.j av a 2 s . c o m*/ */ public static String regexpExtract(String str, String regex, int extractIndex) { if (extractIndex < 0) { return null; } try { Matcher m = REGEXP_PATTERN_CACHE.get(regex).matcher(str); if (m.find()) { MatchResult mr = m.toMatchResult(); return mr.group(extractIndex); } return null; } catch (Exception e) { LOG.error(String.format("Exception in regexpExtract('%s', '%s', '%d')", str, regex, extractIndex), e); return null; } }
From source file:org.jenkinsci.plugins.SemanticVersioning.parsing.SbtParser.java
public AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException { File file = new File(workspace + "/" + BUILD_DEFINITION_FILENAME); if (file.exists()) { String content = FileUtils.readFileToString(file); if (content == null || content.length() <= 0) { throw new InvalidBuildFileFormatException( "'" + BUILD_DEFINITION_FILENAME + "' is not a valid SBT build definition file."); } else {//w w w . j ava2 s. c o m String version; Pattern pattern = Pattern.compile("version\\s*:=\\s*\"([^\"]*)\"", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(content); if (matcher.find()) { version = matcher.toMatchResult().group(1); this.logger.info("SbtParser::extractAppVersion => " + version); } else { throw new InvalidBuildFileFormatException( "No version information found in " + BUILD_DEFINITION_FILENAME); } return AppVersion.parse(version); } } else { throw new FileNotFoundException("'" + BUILD_DEFINITION_FILENAME + "' was not found."); } }
From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritHtmlProcessor.java
/** * Parses the configuration from <code>text</code>. *///from w w w.j av a2s .c o m private void parse(String text) { Pattern p = Pattern.compile("var gerrit_hostpagedata=\\{(\"version\":\"([^\"]+)\",)?\"config\":"); //$NON-NLS-1$ String configXsrfToken = "hostpagedata.xsrfToken=\""; //$NON-NLS-1$ String configXGerritAuth = "hostpagedata.xGerritAuth=\""; //$NON-NLS-1$ String[] tokens = text.split(";gerrit_"); //$NON-NLS-1$ for (String token : tokens) { Matcher m = p.matcher(token); if (m.find()) { token = token.substring(m.toMatchResult().group(0).length()); // remove closing } token = token.substring(0, token.length() - 1); this.config = gerritConfigFromString(token); } else if (token.startsWith(configXsrfToken)) { token = token.substring(configXsrfToken.length()); // remove closing " token = token.substring(0, token.length() - 1); this.xsrfKey = token; } else if (token.startsWith(configXGerritAuth)) { token = token.substring(configXGerritAuth.length()); // remove closing " token = token.substring(0, token.length() - 1); this.xGerritAuth = token; } } }