Java Code Examples for java.util.regex.Matcher#groupCount()

The following examples show how to use java.util.regex.Matcher#groupCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AntPathMatcher.java    From xxl-sso with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Main entry point.
 * @return {@code true} if the string matches against the pattern, or {@code false} otherwise.
 */
public boolean matchStrings(String str, Map<String, String> uriTemplateVariables) {
	Matcher matcher = this.pattern.matcher(str);
	if (matcher.matches()) {
		if (uriTemplateVariables != null) {
			// SPR-8455
			if (this.variableNames.size() != matcher.groupCount()) {
				throw new IllegalArgumentException("The number of capturing groups in the pattern segment " +
						this.pattern + " does not match the number of URI template variables it defines, " +
						"which can occur if capturing groups are used in a URI template regex. " +
						"Use non-capturing groups instead.");
			}
			for (int i = 1; i <= matcher.groupCount(); i++) {
				String name = this.variableNames.get(i - 1);
				String value = matcher.group(i);
				uriTemplateVariables.put(name, value);
			}
		}
		return true;
	}
	else {
		return false;
	}
}
 
Example 2
Source File: TriggerEntry.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
private List<String> parseTriggerEntry(String triggerEntry) {
    List<String> list = new LinkedList<String>();
    // Tokenizing by whitespace and content inside quotes.
    if (triggerEntry != null) {
        // Split the string by whitespace and sequences of characters that
        // begin and end with a quote.
        Pattern pattern = Pattern.compile(TRIGGER_ENTRY_TOKEN_REGEX_PATTERN);
        Matcher regexMatcher = pattern.matcher(triggerEntry);
        while (regexMatcher.find()) {
            if (regexMatcher.groupCount() > 0) {
                if (regexMatcher.group(1) != null) {
                    // Add double-quoted string without the quotes.
                    list.add(regexMatcher.group(1));
                } else if (regexMatcher.group(2) != null) {
                    // Add single-quoted string without the quotes.
                    list.add(regexMatcher.group(2));
                } else {
                    // Add unquoted word
                    list.add(regexMatcher.group());
                }
            }
        }
    }
    return list;
}
 
Example 3
Source File: MovieParser.java    From android-vlc-remote with GNU General Public License v3.0 6 votes vote down vote up
public Movie parse(String path) {
    Movie movie;
    String fileName = File.baseName(path);
    for(Pattern p : patternList) {
        Matcher m = p.matcher(fileName);
        if (m.find()) {
            movie = new Movie();
            movie.setMovieName(StringUtil.formatMatch(m.group(1)));
            if(m.groupCount() == 4) {
                movie.setYear(Integer.valueOf(m.group(2)));
                movie.setQuality(m.group(3));
                movie.setSource(VideoSources.getFormattedSource(m.group(4)));
            } else if(m.groupCount() == 3) {
                movie.setQuality(m.group(2));
                movie.setSource(VideoSources.getFormattedSource(m.group(3)));
            } else {
                movie.setQuality(m.group(2));
            }
            return movie;
        }
    }
    return null;
}
 
Example 4
Source File: NativeStackCallInfo.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Basic constructor with library, method, and sourcefile information
 *
 * @param address address of this stack frame
 * @param lib The name of the library
 * @param method the name of the method
 * @param sourceFile the name of the source file and the line number
 * as "[sourcefile]:[fileNumber]"
 */
public NativeStackCallInfo(long address, String lib, String method, String sourceFile) {
    mAddress = address;
    mLibrary = lib;
    mMethod = method;

    Matcher m = SOURCE_NAME_PATTERN.matcher(sourceFile);
    if (m.matches()) {
        mSourceFile = m.group(1);
        try {
            mLineNumber = Integer.parseInt(m.group(2));
        } catch (NumberFormatException e) {
            // do nothing, the line number will stay at -1
        }
        if (m.groupCount() == 3) {
            // A discriminator was found, add that in the source file name.
            mSourceFile += m.group(3);
        }
    } else {
        mSourceFile = sourceFile;
    }
}
 
Example 5
Source File: AntPathMatcher.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Main entry point.
 * 
 * @return {@code true} if the string matches against the pattern, or
 *         {@code false} otherwise.
 */
public boolean matchStrings(String str, Map<String, String> uriTemplateVariables) {
	Matcher matcher = this.pattern.matcher(str);
	if (matcher.matches()) {
		if (uriTemplateVariables != null) {
			// SPR-8455
			if (this.variableNames.size() != matcher.groupCount()) {
				throw new IllegalArgumentException("The number of capturing groups in the pattern segment " + this.pattern
						+ " does not match the number of URI template variables it defines, "
						+ "which can occur if capturing groups are used in a URI template regex. "
						+ "Use non-capturing groups instead.");
			}
			for (int i = 1; i <= matcher.groupCount(); i++) {
				String name = this.variableNames.get(i - 1);
				String value = matcher.group(i);
				uriTemplateVariables.put(name, value);
			}
		}
		return true;
	} else {
		return false;
	}
}
 
Example 6
Source File: QueryNodeRegex.java    From Extractor with MIT License 6 votes vote down vote up
@Override
public byte[] unpackData(byte[] context) {
    String contextString = Globals.helpers.bytesToString(context);

    Pattern pattern = Pattern.compile("(.*)(" + setting[0] + ")(.*)");
    Matcher matcher = pattern.matcher(contextString);
    
    if (matcher.find() && matcher.groupCount() == 4)
    {
        // String prefix = c.substring(0, matcher.start(3));
        // String suffix = c.substring(matcher.end(3));
        String d = matcher.group(3);
        
        return d.getBytes();
    }

    return "noData".getBytes();
    
}
 
Example 7
Source File: StringUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static String getFirstFound(String contents, String regex) {
    if (isEmpty(regex) || isEmpty(contents)) {
        return null;
    }
    Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CASE);
    Matcher matcher = pattern.matcher(contents);

    if (matcher.find()) {
        if (matcher.groupCount() > 0) {
            return matcher.group(1);
        } else {
            return matcher.group();
        }
    }
    return null;
}
 
Example 8
Source File: CssPropertySignature.java    From caja with Apache License 2.0 6 votes vote down vote up
static ListIterator<String> tokenizeSignature(String sig) {
  List<String> toks = new ArrayList<String>();
  while (!"".equals(sig)) {
    boolean match = false;
    for (Pattern p : TOKENS) {
      Matcher m = p.matcher(sig);
      if (m.find()) {
        if (m.groupCount() > 0) { toks.add(m.group(1)); }
        sig = sig.substring(m.end(0));
        match = true;
        break;
      }
    }
    if (!match) { throw new IllegalArgumentException(sig); }
  }
  return toks.listIterator();
}
 
Example 9
Source File: EnforceVersionsMojo.java    From gitflow-helper-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void checkReleaseTypeBranchVersion(final GitBranchInfo branchInfo, final Matcher gitMatcher) throws MojoFailureException {
    // RELEASE, HOTFIX and SUPPORT branches require a match of the maven project version to the subgroup.
    // Depending on the value of the 'releaseBranchMatchType' param, it's either 'equals' or 'startsWith'.
    if ("equals".equals(releaseBranchMatchType)) {
        // HOTFIX and RELEASE branches require an exact match to the last subgroup.
        if ((GitBranchType.RELEASE.equals(branchInfo.getType()) || GitBranchType.HOTFIX.equals(branchInfo.getType())) && !gitMatcher.group(gitMatcher.groupCount()).trim().equals(project.getVersion().trim())) {
            throw new MojoFailureException("The current git branch: [" + branchInfo.getName() + "] expected the maven project version to be: [" + gitMatcher.group(gitMatcher.groupCount()).trim() + "], but the maven project version is: [" + project.getVersion() + "]");
        }

        // SUPPORT branches require a 'starts with' match of the maven project version to the subgroup.
        // ex: /origin/support/3.1 must have a maven version that starts with "3.1", ala: "3.1.2"
        if (GitBranchType.SUPPORT.equals(branchInfo.getType()) && !project.getVersion().startsWith(gitMatcher.group(gitMatcher.groupCount()).trim())) {
            throw new MojoFailureException("The current git branch: [" + branchInfo.getName() + "] expected the maven project version to start with: [" + gitMatcher.group(gitMatcher.groupCount()).trim() + "], but the maven project version is: [" + project.getVersion() + "]");
        }
    } else { // "startsWith"
        // ex: /origin/release/3.1 must have a maven version that starts with "3.1", ala: "3.1.2"
        if (gitMatcher.groupCount() > 0 && !GitBranchType.MASTER.equals(branchInfo.getType())) {
            String releaseBranchVersion = gitMatcher.group(gitMatcher.groupCount()).trim();
            // Type check always returns true, as it's in VERSIONED_TYPES and not MASTER, but it's handy documentation
            if ((GitBranchType.RELEASE.equals(branchInfo.getType()) || GitBranchType.HOTFIX.equals(branchInfo.getType()) || GitBranchType.SUPPORT.equals(branchInfo.getType())) && !project.getVersion().startsWith(releaseBranchVersion)) {
                throw new MojoFailureException("The current git branch: [" + branchInfo.getName() + "] expected the maven project version to start with: [" + releaseBranchVersion + "], but the maven project version is: [" + project.getVersion() + "]");
            }
        }
    }
}
 
Example 10
Source File: Translator.java    From bookish with MIT License 5 votes vote down vote up
public static List<String> extract(Pattern pattern, String text) {
	Matcher m = pattern.matcher(text);
	List<String> elements = new ArrayList<>();
	if ( m.matches() ) {
		for (int i = 1; i <= m.groupCount(); i++) {
			elements.add(m.group(i));
		}
	}
	return elements;
}
 
Example 11
Source File: FileBackup.java    From fluency with Apache License 2.0 5 votes vote down vote up
public List<SavedBuffer> getSavedFiles()
{
    File[] files = backupDir.listFiles();
    if (files == null) {
        LOG.warn("Failed to list the backup directory. {}", backupDir);
        return new ArrayList<>();
    }

    LOG.debug("Checking backup files. files.length={}", files.length);
    ArrayList<SavedBuffer> savedBuffers = new ArrayList<>();
    for (File f : files) {
        Matcher matcher = pattern.matcher(f.getName());
        if (matcher.find()) {
            if (matcher.groupCount() != 1) {
                LOG.warn("Invalid backup filename: file={}", f.getName());
            }
            else {
                String concatParams = matcher.group(1);
                String[] params = concatParams.split(PARAM_DELIM_IN_FILENAME);
                LinkedList<String> paramList = new LinkedList<>(Arrays.asList(params));
                LOG.debug("Saved buffer params={}", paramList);
                paramList.removeLast();
                savedBuffers.add(new SavedBuffer(f, paramList));
            }
        }
        else {
            LOG.trace("Found a file in backup dir, but the file path doesn't match the pattern. file={}", f.getAbsolutePath());
        }
    }
    return savedBuffers;
}
 
Example 12
Source File: HttpFirstLineDissector.java    From logparser with Apache License 2.0 5 votes vote down vote up
@Override
public void dissect(final Parsable<?> parsable, final String inputname) throws DissectionFailure {
    final ParsedField field = parsable.getParsableField(HTTP_FIRSTLINE, inputname);

    final String fieldValue = field.getValue().getString();
    if (fieldValue == null || fieldValue.isEmpty() || "-".equals(fieldValue)){
        return; // Nothing to do here
    }

    // Now we create a matcher for this line
    Matcher matcher = firstlineSplitter.matcher(fieldValue);

    // Is it all as expected?
    boolean matches = matcher.find();

    if (matches && matcher.groupCount() == 3) {
        outputDissection(parsable, inputname, "HTTP.METHOD", "method", matcher, 1);
        outputDissection(parsable, inputname, "HTTP.URI", "uri", matcher, 2);
        outputDissection(parsable, inputname, "HTTP.PROTOCOL_VERSION", "protocol", matcher, 3);
        return;
    }

    // In the scenario that the actual URI is too long the last part ("HTTP/1.1") may have been cut off by the
    // Apache HTTPD webserver. To still be able to parse these we try that pattern too

    // Now we create a matcher for this line
    matcher = tooLongFirstlineSplitter.matcher(fieldValue);

    // Is it all as expected?
    matches = matcher.find();

    if (matches && matcher.groupCount() == 2) {
        outputDissection(parsable, inputname, "HTTP.METHOD", "method", matcher, 1);
        outputDissection(parsable, inputname, "HTTP.URI", "uri", matcher, 2);
        parsable.addDissection(inputname, "HTTP.PROTOCOL_VERSION", "protocol", (String) null);
    }
}
 
Example 13
Source File: Container.java    From pegasus with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the mount and populates the internal member variables that can be accessed via the
 * appropriate accessor methods
 *
 * @param mount point string as src-mp:dest-mp:options
 */
public final void parse(String mount) {
    Matcher m = mPattern.matcher(mount);
    if (m.matches()) {
        this.setSourceDirectory(m.group(1));
        this.setDestinationDirectory(m.group(2));
        if (m.groupCount() == 4) {
            this.setMountOptions(m.group(4));
        }
    } else {
        throw new RuntimeException("Unable to parse mount " + mount);
    }
}
 
Example 14
Source File: HtmlField.java    From jspoon with MIT License 5 votes vote down vote up
private <U> String getValue(Element node, Class<U> fieldType) {
    if (node == null) {
        return spec.getDefaultValue();
    }
    String value;
    switch (spec.getAttribute()) {
    case "":
    case "text":
        value = node.text();
        break;
    case "html":
    case "innerHtml":
        value = node.html();
        break;
    case "outerHtml":
        value = node.outerHtml();
        break;
    default:
        value = node.attr(spec.getAttribute());
        break;
    }
    if (spec.getRegex() != null) {
        Pattern pattern = Pattern.compile(spec.getRegex());
        Matcher matcher = pattern.matcher(value);
        if (matcher.find()) {
            value = (matcher.groupCount() > 0) ? matcher.group(1) : spec.getDefaultValue();
            if (value == null || value.isEmpty()) {
                value = spec.getDefaultValue();
            }
        }
    }
    return value;
}
 
Example 15
Source File: MemoryFormatUtils.java    From dr-elephant with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a formatted string into a long value in bytes.
 * This method handles
 *
 * @param formattedString The string to convert
 * @return The bytes value
 */
public static long stringToBytes(String formattedString) {
  if (formattedString == null) {
    return 0L;
  }

  Matcher matcher = REGEX_MATCHER.matcher(formattedString.replace(",",""));
  if (!matcher.matches()) {
    throw new IllegalArgumentException(
        "The formatted string [" + formattedString + "] does not match with the regex /" + REGEX_MATCHER.toString()
            + "/");
  }
  if (matcher.groupCount() != 1 && matcher.groupCount() != 2) {
    throw new IllegalArgumentException();
  }

  double numPart = Double.parseDouble(matcher.group(1));
  if (numPart < 0) {
    throw new IllegalArgumentException("The number part of the memory cannot be less than zero: [" + numPart + "].");
  }
  String unitPart = matcher.groupCount() == 2 ? matcher.group(2).toUpperCase() : "";
  if (!unitPart.endsWith("B")) {
    unitPart += "B";
  }
  for (int i = 0; i < UNITS.length; i++) {
    if (unitPart.equals(UNITS[i].getName())) {
      return (long) (numPart * UNITS[i].getBytes());
    }
  }
  throw new IllegalArgumentException("The formatted string [" + formattedString + "] 's unit part [" + unitPart
      + "] does not match any unit. The supported units are (case-insensitive, and also the 'B' is ignorable): ["
      + StringUtils.join(UNITS) + "].");
}
 
Example 16
Source File: NetBeansUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Get netbeans user directory as it is written in netbeans.conf
 * @param nbLocation NetBeans home directory
 * @throws IOException if can`t get netbeans default userdir
 */
private static String getNetBeansUserDir(File nbLocation) throws IOException {
    File netbeansconf = new File(nbLocation, NETBEANS_CONF);
    String contents = FileUtils.readFile(netbeansconf);
    Matcher matcher = Pattern.compile(
            NEW_LINE_PATTERN + SPACES_PATTERN +
            NETBEANS_USERDIR +
            "\"(.*?)\"").matcher(contents);
    if(matcher.find() && matcher.groupCount() == 1) {
        return matcher.group(1);
    } else {
        throw new IOException(StringUtils.format(
                ERROR_CANNOT_GET_USERDIR_STRING,netbeansconf));
    }
}
 
Example 17
Source File: BDDStepMatcherFactory.java    From qaf with MIT License 5 votes vote down vote up
@Override
public List<String[]> getArgsFromCall(String stepDescription, String stepCall, Map<String, Object> context) {
	List<String[]> args = new ArrayList<String[]>();
	stepCall = replaceParams(stepCall, context);
	//stepCall = quoteParams(stepCall);
	Matcher matcher = getMatcher(stepDescription, stepCall);
	while (matcher.find()) {
		for (int i = 1; i <= matcher.groupCount(); i++) {
			String arg = matcher.group(i);
			args.add(new String[] { arg, ParamType.getType(arg).name() });
		}
	}
	return args;
}
 
Example 18
Source File: Elasticsearch5SearchIndex.java    From vertexium with Apache License 2.0 5 votes vote down vote up
private String removeVisibilityFromPropertyNameWithTypeSuffix(String string) {
    Matcher m = PROPERTY_NAME_PATTERN.matcher(string);
    if (m.matches()) {
        if (m.groupCount() >= 4 && m.group(4) != null) {
            string = m.group(1) + m.group(4);
        } else {
            string = m.group(1);
        }
    }
    return string;
}
 
Example 19
Source File: PipelineGroupsTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void assertDuplicateNameErrorOnPipeline(PipelineConfig pipeline, List<String> expectedSources, int sourceCount) {
    assertThat(pipeline.errors().isEmpty(), is(false));
    String errorMessage = pipeline.errors().on(PipelineConfig.NAME);
    assertThat(errorMessage, containsString("You have defined multiple pipelines named 'pipeline1'. Pipeline names must be unique. Source(s):"));
    Matcher matcher = Pattern.compile("^.*\\[(.*),\\s(.*),\\s(.*)\\].*$").matcher(errorMessage);
    assertThat(matcher.matches(), is(true));
    assertThat(matcher.groupCount(), is(sourceCount));
    List<String> actualSources = new ArrayList<>();
    for (int i = 1; i <= matcher.groupCount(); i++) {
        actualSources.add(matcher.group(i));
    }
    assertThat(actualSources.containsAll(expectedSources), is(true));
}
 
Example 20
Source File: StoreFileInfo.java    From hbase with Apache License 2.0 4 votes vote down vote up
public static boolean isHFile(final String fileName) {
  Matcher m = HFILE_NAME_PATTERN.matcher(fileName);
  return m.matches() && m.groupCount() > 0;
}