Example usage for java.util.regex MatchResult group

List of usage examples for java.util.regex MatchResult group

Introduction

In this page you can find the example usage for java.util.regex MatchResult group.

Prototype

public String group(int group);

Source Link

Document

Returns the input subsequence captured by the given group during the previous match operation.

Usage

From source file:magicware.scm.redmine.tools.RedmineClient.java

public String createNewIssue(String newIssue) throws ClientProtocolException, IOException {
    HttpPost httpPost = null;/*from  w ww  . j  a v  a 2 s  .c  om*/
    String newIssueId = null;
    try {
        log.trace(newIssue);
        httpPost = new HttpPost(this.context + "/issues.json");
        httpPost.setEntity(new StringEntity(newIssue, "application/json", HTTP.UTF_8));
        log.debug("executing post request " + httpPost.getURI());

        // ???
        RdeminResponse rdeminResponse = getRdeminResponse(httpPost);

        if (rdeminResponse.isResponseOK()) {
            Matcher m = Pattern.compile(Constants.ISSUE_ID_VALUE_EXP).matcher(rdeminResponse.getContent());
            while (m.find()) {
                MatchResult mr = m.toMatchResult();
                newIssueId = mr.group(1).trim();
            }
        }
        return newIssueId;

    } finally {
        if (httpPost != null)
            httpPost.abort();
    }
}

From source file:com.edgenius.wiki.render.filter.HeadingFilter.java

@SuppressWarnings("unchecked")
@Override// w  ww.  ja v a2  s . c o m
public void replace(StringBuffer buffer, MatchResult matchResult, RenderContext context) {
    int i = matchResult.groupCount();
    if (i < 3) {
        //failure tolerance
        buffer.append(matchResult.group(0));
        return;
    }
    String lead = matchResult.group(1);
    String level = matchResult.group(3);
    //please note this piece text should be regionKey rather than original text.
    String title = matchResult.group(4);

    String tail = matchResult.group(5);

    List<HeadingModel> list = (List<HeadingModel>) context.getGlobalParam(TOCMacro.class.getName());
    if (list == null) {
        list = new ArrayList<HeadingModel>();
        context.putGlobalParam(TOCMacro.class.getName(), list);
    }
    //put anchor data to RenderContext.global for later TOCMacro render (if page contain TOCMacro) 
    //The anchor must not change for each render - otherwise it is can not be redirect again once page refresh.
    String headerAnchor = "HeaderAnchor" + list.size();
    HeadingModel head = new HeadingModel();
    head.setOrder(context.createIncremetalKey());
    head.setLevel(NumberUtils.toInt(level));
    head.setTitle(title);
    head.setAnchor(headerAnchor);

    list.add(head);

    //group(2): number of heading, 
    buffer.append(formatter.format(new Object[] { lead, level, title, tail, headerAnchor }));
}

From source file:magicware.scm.redmine.tools.RedmineClient.java

public int queryIssue(String projectId, String fieldId, String keyNo)
        throws ClientProtocolException, IOException {

    HttpGet httpGet = null;//w w w. j a  v a  2 s  .co m
    try {

        int count = 0;
        StringBuilder uri = new StringBuilder();

        uri.append(this.context).append("/issues.json?").append("project_id=").append(projectId)
                .append("&status_id=*&").append(fieldId).append("=").append(keyNo);

        httpGet = new HttpGet(uri.toString());
        log.debug("executing get request " + httpGet.getURI());

        // ???
        RdeminResponse rdeminResponse = getRdeminResponse(httpGet);

        if (rdeminResponse.isResponseOK()) {
            Matcher m = Pattern.compile(Constants.ISSUE_COUNT_VALUE_EXP).matcher(rdeminResponse.getContent());
            while (m.find()) {
                MatchResult mr = m.toMatchResult();
                count = Integer.valueOf(mr.group(1).trim());
            }
            log.debug("count of issue[" + keyNo + "] -> " + count);
        } else {
            throw new RuntimeException(
                    "??????????" + rdeminResponse.getContent());
        }

        return count;

    } finally {
        if (httpGet != null)
            httpGet.abort();
    }
}

From source file:com.log4ic.compressor.utils.Compressor.java

/**
 * URL?//from   ww w  . j a va 2s .com
 *
 * @param code
 * @param fileUrl
 * @param type
 * @param fileDomain
 * @return
 */
public static String fixUrlPath(HttpServletRequest req, String code, String fileUrl, FileType type,
        String fileDomain) {

    StringBuilder codeBuffer = new StringBuilder();
    switch (type) {
    case GSS:
    case CSS:
    case LESS:
    case MSS:
        logger.debug("URL?...");
        Pattern pattern = Pattern.compile("url\\(\\s*(?!['\"]?(?:data:|about:|#|@))([^)]+)\\)",
                Pattern.CASE_INSENSITIVE);

        Matcher matcher = pattern.matcher(code);

        String[] codeFragments = pattern.split(code);

        fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/") + 1);

        int i = 0;
        while (matcher.find()) {
            codeBuffer.append(codeFragments[i]);
            codeBuffer.append("url(");
            MatchResult result = matcher.toMatchResult();
            String url = result.group(1).replaceAll("'|\"", "");
            //???
            if (!HttpUtils.isHttpProtocol(url) && !url.startsWith("/")) {
                url = URI.create(fileUrl + url).normalize().toASCIIString();//?URL
            }

            //??url?http?)??????
            if (StringUtils.isNotBlank(fileDomain) && !HttpUtils.isHttpProtocol(url)) {
                if (!fileDomain.endsWith("/") && !url.startsWith("/")) {
                    fileDomain = fileDomain + "/";
                } else if (fileDomain.endsWith("/") && url.startsWith("/")) {
                    url = url.substring(1);
                }
                if (!HttpUtils.isHttpProtocol(fileDomain)) {
                    fileDomain = "http://" + fileDomain;
                }
                url = fileDomain + url;
            } else {
                url = req.getContextPath() + (url.startsWith("/") ? url : "/" + url);
            }
            codeBuffer.append(url);
            codeBuffer.append(")");
            i++;
        }
        if (i == 0) {
            return code;
        } else {
            if (codeFragments.length > i && StringUtils.isNotBlank(codeFragments[i])) {
                codeBuffer.append(codeFragments[i]);
            }
        }
        logger.debug("URL?...");
        break;
    default:
        return code;
    }
    return codeBuffer.toString();
}

From source file:alfio.controller.api.AdminApiController.java

@RequestMapping(value = "/events/{eventName}/pending-payments/bulk-confirmation", method = POST)
public List<Triple<Boolean, String, String>> bulkConfirmation(@PathVariable("eventName") String eventName,
        Principal principal, @RequestParam("file") MultipartFile file) throws IOException {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
        String username = principal.getName();
        return reader.lines().map(line -> {
            String reservationID = null;
            try (Scanner scanner = new Scanner(line)) {
                scanner.findInLine("([a-zA-Z0-9\\-]+);(\\d+(\\.\\d+)?)");
                MatchResult match = scanner.match();
                reservationID = match.group(1);
                eventManager.confirmPayment(eventName, reservationID, new BigDecimal(match.group(2)), username);
                return Triple.of(Boolean.TRUE, reservationID, "");
            } catch (Exception e) {
                return Triple.of(Boolean.FALSE, Optional.ofNullable(reservationID).orElse(""), e.getMessage());
            }//from   ww w .j  a va  2  s  .  c  o  m
        }).collect(Collectors.toList());
    }
}

From source file:edu.cmu.lti.oaqa.framework.eval.gs.PassageGoldStandardFilePersistenceProvider.java

@Override
public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams)
        throws ResourceInitializationException {
    boolean ret = super.initialize(aSpecifier, aAdditionalParams);
    String dataset = (String) getParameterValue("DataSet");
    Pattern lineSyntaxPattern = Pattern.compile((String) getParameterValue("LineSyntax"));
    try {/*  w  ww  .j  ava2  s  .  c  o m*/
        Resource[] resources = resolver.getResources((String) getParameterValue("PathPattern"));
        for (Resource resource : resources) {
            Scanner scanner = new Scanner(resource.getInputStream());
            while (scanner.findInLine(lineSyntaxPattern) != null) {
                MatchResult result = scanner.match();
                DatasetSequenceId id = new DatasetSequenceId(dataset, result.group(1));
                List<GoldStandardSpan> list = id2gsSpans.get(id);
                if (list == null) {
                    list = new ArrayList<GoldStandardSpan>();
                    id2gsSpans.put(id, list);
                }
                GoldStandardSpan annotation = new GoldStandardSpan(result.group(2),
                        Integer.parseInt(result.group(3)), Integer.parseInt(result.group(4)), result.group(5));
                list.add(annotation);
                if (scanner.hasNextLine()) {
                    scanner.nextLine();
                } else {
                    break;
                }
            }
            scanner.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:magicware.scm.redmine.tools.IssueSyncApp.java

public void execute(SyncItem syncItem) throws IOException, InvalidFormatException {

    FileInputStream in = null;//from  w w w  .j av a 2s.  c  o  m

    try {

        // ?JSON??
        String issueTemplate = FileUtils.readFileAsString(syncItem.getJsonTemplate());

        // ???
        Matcher m = Pattern.compile(Constants.ISSUE_FIELD_VALUE_EXP).matcher(issueTemplate);

        List<MatchResult> mrList = new ArrayList<MatchResult>();

        while (m.find()) {
            MatchResult mr = m.toMatchResult();
            mrList.add(mr);
        }

        // ????
        in = new FileInputStream(syncItem.getFilePath());
        Workbook wb = WorkbookFactory.create(in);

        FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

        Sheet sheet = wb.getSheet(syncItem.getSheetName());
        Row row = null;
        Cell cell = null;

        List<String> issues = new ArrayList<String>();

        // ?????
        for (int i = sheet.getLastRowNum(); i >= (syncItem.getKeyRowBeginIdx() > 0
                ? (syncItem.getKeyRowBeginIdx() - 1)
                : 0); i--) {
            // ????
            row = sheet.getRow(i);

            if (row != null) {

                String keyNo = ExcelUtils.getCellContent(row.getCell(syncItem.getKeyColumnIdx() - 1),
                        evaluator);

                // ??????????
                if (StringUtils.isBlank(keyNo)) {
                    break;
                }

                // ????
                if (redmineClient.queryIssue(syncItem.getProjectId(), syncItem.getKeyFiledId(), keyNo) == 0) {
                    StringBuilder newIssue = new StringBuilder();
                    int eolIdx = 0;
                    for (MatchResult matchResult : mrList) {

                        newIssue.append(issueTemplate.substring(eolIdx, matchResult.start()));

                        int cellIndex = Integer.valueOf(matchResult.group(1)) - 1;
                        cell = row.getCell(cellIndex);
                        String cellvalue = ExcelUtils.getCellContent(cell, evaluator);

                        // ?
                        String valueMapStr = matchResult.group(3);
                        Map<String, String> valueMap = null;
                        if (valueMapStr != null) {
                            valueMap = JSON.decode(valueMapStr);
                            if (StringUtils.isNotEmpty(cellvalue) && valueMap.containsKey(cellvalue)) {
                                cellvalue = valueMap.get(cellvalue);
                            } else {
                                cellvalue = valueMap.get("default");
                            }
                        }

                        if (StringUtils.isNotEmpty(cellvalue)) {
                            cellvalue = StringEscapeUtils.escapeJavaScript(cellvalue);
                            newIssue.append(cellvalue);
                        }
                        eolIdx = matchResult.end();
                    }
                    newIssue.append(issueTemplate.substring(eolIdx));
                    issues.add(newIssue.toString());
                } else {
                    // ???
                    break;
                }
            }
        }

        for (int i = issues.size() - 1; i >= 0; i--) {
            Map<String, Issue> issueMap = JSON.decode(issues.get(i));
            log.debug("create new issue >>>");
            log.debug(JSON.encode(issueMap, true));
            redmineClient.createNewIssue(issues.get(i));
        }

    } finally {
        if (in != null) {
            in.close();
            in = null;
        }
    }
}

From source file:com.edgenius.wiki.render.filter.ListFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult result, RenderContext context) {
    try {/*from w  w  w.j a  v  a  2 s. c o m*/
        //this text does not contain leading newline (\n) but contain all tailed newline.
        String wholeText = result.group(0);

        BufferedReader reader = new BufferedReader(new StringReader(wholeText));
        addList(buffer, reader);

        //append tailing newlines
        buffer.append(result.group(3));
    } catch (Exception e) {
        log.warn("ListFilter: unable get list content", e);
    }
}

From source file:com.edgenius.wiki.render.filter.TableFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult result, RenderContext context) {
    try {/*  w  w w . java2s .  c  o  m*/
        //this text does not contain leading newline (\n) but contain all tailed newline.
        //this text may contain multiple list which is separate by multiple newline 
        String wholeText = result.group(0);

        BufferedReader reader = new BufferedReader(new StringReader(wholeText));
        buildTable(buffer, reader);

        //don't eat last \n as NewlineFitler need it. do not need consider multiple empty line case, as it will do in addList().
        if (!StringUtil.endOfAny(buffer.toString(), new String[] { "\r", "\n" })
                && StringUtil.endOfAny(wholeText, new String[] { "\r", "\n" }))
            buffer.append("\n");
    } catch (Exception e) {
        log.warn("TableFilter: unable get table content", e);
    }

}

From source file:de.sub.goobi.helper.VariableReplacerWithoutHibernate.java

/**
 * Variablen innerhalb eines Strings ersetzen. Dabei vergleichbar zu Ant die
 * Variablen durchlaufen und aus dem Digital Document holen.
 *//*from   w w w . j a v  a2s . c  o  m*/
public String replace(String inString) {
    if (inString == null) {
        return "";
    }

    /*
     * replace metadata, usage: $(meta.firstchild.METADATANAME)
     */
    for (MatchResult r : findRegexMatches(this.namespaceMeta, inString)) {
        if (r.group(1).toLowerCase().startsWith("firstchild.")) {
            inString = inString.replace(r.group(),
                    getMetadataFromDigitalDocument(MetadataLevel.FIRSTCHILD, r.group(1).substring(11)));
        } else if (r.group(1).toLowerCase().startsWith("topstruct.")) {
            inString = inString.replace(r.group(),
                    getMetadataFromDigitalDocument(MetadataLevel.TOPSTRUCT, r.group(1).substring(10)));
        } else {
            inString = inString.replace(r.group(),
                    getMetadataFromDigitalDocument(MetadataLevel.ALL, r.group(1)));
        }
    }

    FolderInformation fi = new FolderInformation(this.process.getId(), this.process.getTitle());

    String processpath = fi.getProcessDataDirectory().replace("\\", "/");
    String tifpath = fi.getImagesTifDirectory(false).replace("\\", "/");
    String imagepath = fi.getImagesDirectory().replace("\\", "/");
    String origpath = fi.getImagesOrigDirectory(false).replace("\\", "/");
    String metaFile = fi.getMetadataFilePath().replace("\\", "/");
    String ocrBasisPath = fi.getOcrDirectory().replace("\\", "/");
    String ocrPlaintextPath = fi.getTxtDirectory().replace("\\", "/");
    String sourcePath = fi.getSourceDirectory().replace("\\", "/");
    String importPath = fi.getImportDirectory().replace("\\", "/");
    Ruleset ruleset = ProcessManager.getRuleset(this.process.getRulesetId());
    String myprefs = ConfigCore.getParameter("RegelsaetzeVerzeichnis") + ruleset.getFile();

    /*
     * da die Tiffwriter-Scripte einen Pfad ohne endenen Slash haben wollen,
     * wird diese rausgenommen
     */
    if (tifpath.endsWith(File.separator)) {
        tifpath = tifpath.substring(0, tifpath.length() - File.separator.length()).replace("\\", "/");
    }
    if (imagepath.endsWith(File.separator)) {
        imagepath = imagepath.substring(0, imagepath.length() - File.separator.length()).replace("\\", "/");
    }
    if (origpath.endsWith(File.separator)) {
        origpath = origpath.substring(0, origpath.length() - File.separator.length()).replace("\\", "/");
    }
    if (processpath.endsWith(File.separator)) {
        processpath = processpath.substring(0, processpath.length() - File.separator.length()).replace("\\",
                "/");
    }
    if (importPath.endsWith(File.separator)) {
        importPath = importPath.substring(0, importPath.length() - File.separator.length()).replace("\\", "/");
    }
    if (sourcePath.endsWith(File.separator)) {
        sourcePath = sourcePath.substring(0, sourcePath.length() - File.separator.length()).replace("\\", "/");
    }
    if (ocrBasisPath.endsWith(File.separator)) {
        ocrBasisPath = ocrBasisPath.substring(0, ocrBasisPath.length() - File.separator.length()).replace("\\",
                "/");
    }
    if (ocrPlaintextPath.endsWith(File.separator)) {
        ocrPlaintextPath = ocrPlaintextPath.substring(0, ocrPlaintextPath.length() - File.separator.length())
                .replace("\\", "/");
    }
    if (inString.contains("(tifurl)")) {
        if (SystemUtils.IS_OS_WINDOWS) {
            inString = inString.replace("(tifurl)", "file:/" + tifpath);
        } else {
            inString = inString.replace("(tifurl)", "file://" + tifpath);
        }
    }
    if (inString.contains("(origurl)")) {
        if (SystemUtils.IS_OS_WINDOWS) {
            inString = inString.replace("(origurl)", "file:/" + origpath);
        } else {
            inString = inString.replace("(origurl)", "file://" + origpath);
        }
    }
    if (inString.contains("(imageurl)")) {
        if (SystemUtils.IS_OS_WINDOWS) {
            inString = inString.replace("(imageurl)", "file:/" + imagepath);
        } else {
            inString = inString.replace("(imageurl)", "file://" + imagepath);
        }
    }

    if (inString.contains("(tifpath)")) {
        inString = inString.replace("(tifpath)", tifpath);
    }
    if (inString.contains("(origpath)")) {
        inString = inString.replace("(origpath)", origpath);
    }
    if (inString.contains("(imagepath)")) {
        inString = inString.replace("(imagepath)", imagepath);
    }
    if (inString.contains("(processpath)")) {
        inString = inString.replace("(processpath)", processpath);
    }
    if (inString.contains("(importpath)")) {
        inString = inString.replace("(importpath)", importPath);
    }
    if (inString.contains("(sourcepath)")) {
        inString = inString.replace("(sourcepath)", sourcePath);
    }
    if (inString.contains("(ocrbasispath)")) {
        inString = inString.replace("(ocrbasispath)", ocrBasisPath);
    }
    if (inString.contains("(ocrplaintextpath)")) {
        inString = inString.replace("(ocrplaintextpath)", ocrPlaintextPath);
    }
    if (inString.contains("(processtitle)")) {
        inString = inString.replace("(processtitle)", this.process.getTitle());
    }
    if (inString.contains("(processid)")) {
        inString = inString.replace("(processid)", String.valueOf(this.process.getId()));
    }
    if (inString.contains("(metaFile)")) {
        inString = inString.replace("(metaFile)", metaFile);
    }
    if (inString.contains("(prefs)")) {
        inString = inString.replace("(prefs)", myprefs);
    }

    if (this.step != null) {
        String stepId = String.valueOf(this.step.getId());
        String stepname = this.step.getTitle();

        inString = inString.replace("(stepid)", stepId);
        inString = inString.replace("(stepname)", stepname);
    }

    // replace WerkstueckEigenschaft, usage: (product.PROPERTYTITLE)

    for (MatchResult r : findRegexMatches("\\(product\\.([\\w.-]*)\\)", inString)) {
        String propertyTitle = r.group(1);
        List<Property> ppList = ProcessManager.getProductProperties(this.process.getId());
        for (Property pe : ppList) {
            if (pe.getTitle().equalsIgnoreCase(propertyTitle)) {
                inString = inString.replace(r.group(), pe.getValue());
                break;
            }
        }
    }

    // replace Vorlageeigenschaft, usage: (template.PROPERTYTITLE)

    for (MatchResult r : findRegexMatches("\\(template\\.([\\w.-]*)\\)", inString)) {
        String propertyTitle = r.group(1);
        List<Property> ppList = ProcessManager.getTemplateProperties(this.process.getId());
        for (Property pe : ppList) {
            if (pe.getTitle().equalsIgnoreCase(propertyTitle)) {
                inString = inString.replace(r.group(), pe.getValue());
                break;
            }
        }
    }

    // replace Prozesseigenschaft, usage: (process.PROPERTYTITLE)

    for (MatchResult r : findRegexMatches("\\(process\\.([\\w.-]*)\\)", inString)) {
        String propertyTitle = r.group(1);
        List<Property> ppList = ProcessManager.getProcessProperties(this.process.getId());
        for (Property pe : ppList) {
            if (pe.getTitle().equalsIgnoreCase(propertyTitle)) {
                inString = inString.replace(r.group(), pe.getValue());
                break;
            }
        }
    }
    return inString;
}