Java Code Examples for java.util.regex.Matcher

The following are top voted examples for showing how to use java.util.regex.Matcher. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: jentrata-msh   File: Template.java View source code 7 votes vote down vote up
/**
 * Parses the template content and initializes this template.
 */
public void parse() {
    List elements = new ArrayList();

    String regexp = "<!--[\\s]*template-((.*?))[\\s]*-->";
    Pattern p = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(template);
    
    int cur = 0;
    for (int i=0; m.find(); i++) {
        if (m.start()>cur) {
            elements.add(new TemplateElement(template.substring(cur, m.start()), true));
        }
        elements.add(new TemplateElement(m.group(1)));
        cur = m.end();
    }
    if (cur < template.length()) {
        elements.add(new TemplateElement(template.substring(cur, template.length()), true));
    }
    
    iterator = elements.iterator();
}
 
Example 2
Project: Grinnell-DB-Android   File: RequestTask.java View source code 6 votes vote down vote up
private String numberParser(String str) {
	String match = "[0-9]+";
	Pattern pattern = Pattern.compile("-?\\d+");
	Matcher m = pattern.matcher(str);
	while (m.find()) {
		return m.group(0);
	}
	return null;
}
 
Example 3
Project: lettuce   File: ServerCommandTest.java View source code 6 votes vote down vote up
@Test
public void clientKillExtended() throws Exception {

    RedisConnection<String, String> connection2 = client.connect();
    connection2.clientSetname("killme");

    Pattern p = Pattern.compile("^.*addr=([^ ]+).*name=killme.*$", Pattern.MULTILINE | Pattern.DOTALL);
    String clients = redis.clientList();
    Matcher m = p.matcher(clients);

    assertThat(m.matches()).isTrue();
    String addr = m.group(1);
    assertThat(redis.clientKill(KillArgs.Builder.addr(addr).skipme())).isGreaterThan(0);

    assertThat(redis.clientKill(KillArgs.Builder.id(4234))).isEqualTo(0);
    assertThat(redis.clientKill(KillArgs.Builder.typeSlave().id(4234))).isEqualTo(0);
    assertThat(redis.clientKill(KillArgs.Builder.typeNormal().id(4234))).isEqualTo(0);
    assertThat(redis.clientKill(KillArgs.Builder.typePubsub().id(4234))).isEqualTo(0);

    connection2.close();
}
 
Example 4
Project: sslcertx   File: MySQLCallableStatement.java View source code 6 votes vote down vote up
public MySQLCallableStatement(MySQLConnection connection, String query) throws SQLException{
    con = connection;

    query = Utils.nativeSQL(query, ((MySQLConnection)connection).noBackslashEscapes);
    batchIgnoreResult = new BitSet();
    Matcher m = CALLABLE_STATEMENT_PATTERN.matcher(query);
    if(!m.matches())
        throw new SQLSyntaxErrorException("invalid callable syntax");

    //
    boolean isFunction = (m.group(1) != null);
    String procedureName = m.group(2);
    String arguments = m.group(3);
    if (!isFunction) {
        // real stored procedure, generate "CALL PROC(args)", with ? in args replaces by variables
        callQuery = "call " + procedureName + resolveArguments(arguments,1);
    }
    else {
        // function returning result, generate "SELECT FUNC(args) into @_jdbc_var_1
        callQuery = "select " + procedureName + resolveArguments(arguments, 2) + " into " + getVariableName(1);
    }
    callStatement = con.createStatement();

    // Generate set _jdbc_var1=?,....set jdbc_var_n=? prepared statement
    if (parametersCount != 0) {
        StringBuffer sb = new StringBuffer("set ");
        for(int i = 1; i <= parametersCount; i++) {
            if(i > 1) {
                sb.append(",");
            }
            sb.append(getVariableName(i));
            sb.append("=?");
        }
        preparedStatement = con.prepareStatement(sb.toString());
        for(int i=1; i<= parametersCount; i++) {
            preparedStatement.setNull(i, Types.NULL);
        }
    }
    params = new CallParameter[parametersCount+1];
    for(int i=1 ; i <= parametersCount; i++) {
        params[i] = new CallParameter();
    }
    if (isFunction) {
        // the query was in the form {?=call function()}, so the first parameter is always output
        params[1].isOutput = true;
    }
    parameterMetadata = new CallableParameterMetaData(params, con, procedureName, isFunction);
}
 
Example 5
Project: jentrata-msh   File: PayloadCache.java View source code 6 votes vote down vote up
private String encodeFilename(String filename) {
    StringBuffer buffer = new StringBuffer(); 
    if (filename != null) {
        Pattern p = Pattern.compile("[\\\\/:\\*\\?\"\\<\\>\\|\\[\\]%]");
        Matcher m = p.matcher(filename);
        int i = 0;
        while (m.find()) {
            buffer.append(filename.substring(i, m.start()));
            char sc = m.group().charAt(0);
            buffer.append("%").append(Integer.toHexString((int)sc).toUpperCase());
            i = m.end();
        }
        buffer.append(filename.substring(i, filename.length()));
    }
    return buffer.toString();
}
 
Example 6
Project: jentrata-msh   File: StringUtilities.java View source code 6 votes vote down vote up
/**
 * @param string
 * @param regex
 * @param group the <b>one-based</b> index of the target group. 
 * The default group is the zeroth group, which is the whole expression
 * @return each match of the specified group
 */
public static List<String> extractRegexMulti(String string, String regex, int group) {
    List<String> result = new ArrayList<String>();
    
    if (string == null) {
        return result;
    }
    
    Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
    Matcher matcher = pattern.matcher(string);
    
    while (matcher.find()) {
        if (group > matcher.groupCount()) {
        } else {
            result.add(matcher.group(group));
        }
    }
    return result;
}
 
Example 7
Project: TinyProtocolAPI   File: Reflection.java View source code 6 votes vote down vote up
private static String expandVariables(String name) {
	StringBuffer output = new StringBuffer();
	Matcher matcher = MATCH_VARIABLE.matcher(name);

	while (matcher.find()) {
		String variable = matcher.group(1);
		String replacement = "";

		if ("nms".equalsIgnoreCase(variable))
			replacement = NMS_PREFIX;
		else if ("obc".equalsIgnoreCase(variable))
			replacement = OBC_PREFIX;
		else if ("version".equalsIgnoreCase(variable))
			replacement = VERSION;
		else
			throw new IllegalArgumentException("Unknown variable: "
					+ variable);

		if (replacement.length() > 0 && matcher.end() < name.length()
				&& name.charAt(matcher.end()) != '.')
			replacement += ".";
		matcher.appendReplacement(output,
				Matcher.quoteReplacement(replacement));
	}

	matcher.appendTail(output);
	return output.toString();
}
 
Example 8
Project: richfaces   File: ResourceServletMapping.java View source code 6 votes vote down vote up
static String getResourcePath(Resource resource) {
    final StringBuffer buffer = new StringBuffer();

    String ln = Strings.nullToEmpty(resource.getLibraryName());
    if (!ln.isEmpty()) {
        buffer.append(ln).append("/");
    }

    buffer.append(resource.getResourceName());

    try {
        URI originalRequestPath = new URI("path://" + resource.getRequestPath());
        String query = originalRequestPath.getQuery();
        Matcher matcher = LN_PATTERN.matcher(query);
        if (matcher.matches()) {
            ln = matcher.group(2);
            query = matcher.replaceFirst("$1$3");
            matcher = AMP_CLEANUP_PATTERN.matcher(query);
            if (matcher.matches()) {
                query = matcher.replaceAll("$1$2$3");
            }
        }
        if (!query.isEmpty()) {
            buffer.append("?").append(query);
        }
        return buffer.toString();
    } catch (URISyntaxException e) {
        throw new IllegalStateException(String.format("Failed to parse requestPath '%s' for resource '%s': %s",
                resource.getRequestPath(), ResourceKey.create(resource), e.getMessage()), e);
    }
}
 
Example 9
Project: jena   File: NTriple.java View source code 6 votes vote down vote up
/**
 * 
 * Replace any non-legal char (or Z) with ZNN where NN are the hex codes
 * in UTF-8
 * @param anonymousID Is something that corresponds to an XMLName 
 * @return an ascii string that is legal NTriple
 */
public static String escapeNTriple(String anonymousID) {
	Matcher matcher = ntripleBnode.matcher(anonymousID);
	if (matcher.matches())
		return anonymousID;
	matcher.reset();
	StringBuilder rslt = new StringBuilder();
	int lastNotMatched = 0;
	while (matcher.find()) {
		
		String unmatched = anonymousID.substring(lastNotMatched, matcher.start());
		
		rslt.append(escapeUTF8(unmatched));
		lastNotMatched = matcher.end();
		rslt.append(matcher.group());
	}
	rslt.append(escapeUTF8(anonymousID.substring(lastNotMatched)));
	return rslt.toString();
}
 
Example 10
Project: phonegap-geolocation   File: MediaType.java View source code 6 votes vote down vote up
/**
 * Returns a media type for [email protected] string}, or null if [email protected] string} is not a
 * well-formed media type.
 */
public static MediaType parse(String string) {
  Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
  if (!typeSubtype.lookingAt()) return null;
  String type = typeSubtype.group(1).toLowerCase(Locale.US);
  String subtype = typeSubtype.group(2).toLowerCase(Locale.US);

  String charset = null;
  Matcher parameter = PARAMETER.matcher(string);
  for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
    parameter.region(s, string.length());
    if (!parameter.lookingAt()) return null; // This is not a well-formed media type.

    String name = parameter.group(1);
    if (name == null || !name.equalsIgnoreCase("charset")) continue;
    if (charset != null) throw new IllegalArgumentException("Multiple charsets: " + string);
    charset = parameter.group(2) != null
        ? parameter.group(2)  // Value is a token.
        : parameter.group(3); // Value is a quoted string.
  }

  return new MediaType(string, type, subtype, charset);
}
 
Example 11
Project: wso2-synapse   File: PayloadFactoryMediator.java View source code 6 votes vote down vote up
/**
 * Goes through SynapsePath argument list, evaluating each by calling stringValueOf and returns a HashMap String, String
 * array where each item will contain a hash map with key "evaluated expression" and value "SynapsePath type".
 * @param synCtx
 * @return
 */
private HashMap<String, String>[] getArgValues(MessageContext synCtx) {
    HashMap<String, String>[] argValues = new HashMap[pathArgumentList.size()];
    HashMap<String, String> valueMap;
    String value = "";
    for (int i = 0; i < pathArgumentList.size(); ++i) {       /*ToDo use foreach*/
        Argument arg = pathArgumentList.get(i);
        if (arg.getValue() != null) {
            value = arg.getValue();
            if (!isXML(value)) {
                value = StringEscapeUtils.escapeXml(value);
            }
            value = Matcher.quoteReplacement(value);
        } else if (arg.getExpression() != null) {
            value = arg.getExpression().stringValueOf(synCtx);
            if (value != null) {
                // XML escape the result of an expression that produces a literal, if the target format
                // of the payload is XML.
                if (!isXML(value) && !arg.getExpression().getPathType().equals(SynapsePath.JSON_PATH)
                        && XML_TYPE.equals(getType())) {
                    value = StringEscapeUtils.escapeXml(value);
                }
                value = Matcher.quoteReplacement(value);
            } else {
                value = "";
            }
        } else {
            handleException("Unexpected arg type detected", synCtx);
        }
        //value = value.replace(String.valueOf((char) 160), " ").trim();
        valueMap = new HashMap<String, String>();
        if (null != arg.getExpression()) {
            valueMap.put(value, arg.getExpression().getPathType());
        } else {
            valueMap.put(value, SynapsePath.X_PATH);
        }
        argValues[i] = valueMap;
    }
    return argValues;
}
 
Example 12
Project: extFM-Tooling   File: ConsistencyCheckHandler.java View source code 6 votes vote down vote up
private void determineInfo(List<String> paramList, String param, IFile file) {
   String fileName = file.getName();
   // example:
   // documentmanagement.feature_balanced_height2_countChildren2_vpCount10_groupsVP1_2012-03-31-082230484.cluster_FCount_2012-03-31-082231424.featuremapping
   String regex = param + "([0-9])*";
   Pattern pattern = Pattern.compile(regex);
   Matcher matcher = pattern.matcher(fileName);
   while (matcher.find()) {
      MatchResult result = matcher.toMatchResult();
      String match = result.group();
      String number = match.substring(param.length());
      paramList.add(number);
   }
}
 
Example 13
Project: spikes   File: StringUtil.java View source code 6 votes vote down vote up
public static String snakify(String original) {
    if (original == null || original.length() == 0)
        return "";

    StringBuilder builder = new StringBuilder();
    Pattern p = Pattern.compile("[A-Z][a-z0-9]+");
    Matcher m = p.matcher(original);
    String word;
    while (m.find()) {
        word = m.group();
        builder.append(word.toLowerCase());
        if (!m.hitEnd()) {
            builder.append('_');
        }
    }
    if (builder.length() == 0) {
        return original.toLowerCase();
    }
    return builder.toString();
}
 
Example 14
Project: openwayback   File: MementoUtilsTest.java View source code 6 votes vote down vote up
public void testGenerateMementoLinkHeaders() {
	final CaptureSearchResults results = new CaptureSearchResults();
	results.addSearchResult(createCapture("20140101000000"));
	results.addSearchResult(createCapture("20140125000000"));
	results.setClosest(results.getResults().getLast());

	final WaybackRequest wbr = new WaybackRequest();
	wbr.setAccessPoint(accessPoint);
	wbr.setRequestUrl("http://example.com/");

	String result = MementoUtils.generateMementoLinkHeaders(results, wbr, true, true);

	List<String> elements = new ArrayList<String>();
	Matcher m = LINK_ELEMENT_PATTERN.matcher(result);
	while (m.regionStart() < result.length() && m.lookingAt()) {
		elements.add(m.group(1));
		m.region(m.end(), result.length());
	}
	assertEquals(result.length(), m.regionStart());

	// TODO: order doesn't really matter
	assertEquals("<http://example.com/>; rel=\"original\"",
		elements.get(0));
	assertEquals("</web/timemap/link/http://example.com/>; rel=\"timemap\"; type=\"application/link-format\"",
		elements.get(1));
	assertEquals("</web/http://example.com/>; rel=\"timegate\"",
		elements.get(2));
	assertEquals("</web/20140125000000/http://example.com/>; rel=\"last memento\"; datetime=\"Sat, 25 Jan 2014 00:00:00 GMT\"",
		elements.get(3));
	assertEquals("</web/20140101000000/http://example.com/>; rel=\"prev first memento\"; datetime=\"Wed, 01 Jan 2014 00:00:00 GMT\"",
		elements.get(4));
}
 
Example 15
Project: open-mika   File: MatcherTest.java View source code 6 votes vote down vote up
/**
 * @test java.util.regex.Matcher#hasTransparentBounds()
 * test hasTransparentBounds() method.
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "Verifies that hasTransparentBound method returns correct value.",
    method = "hasTransparentBounds",
    args = {}
)  
 */
public void test_hasTransparentBounds() {
    String testPattern = "abb";
    String testString = "ab\nb";
    Pattern pat = Pattern.compile(testPattern);
    Matcher mat = pat.matcher(testString);

    assertFalse("Matcher uses opaque bounds by default",
            mat.hasTransparentBounds());

    Matcher mu = mat.useTransparentBounds(true);
    assertTrue("Incorrect value of anchoring bounds",
            mu.hasTransparentBounds());

    mu = mat.useTransparentBounds(false);
    assertFalse("Incorrect value of anchoring bounds",
            mu.hasTransparentBounds());
}
 
Example 16
Project: open-mika   File: MatcherTest.java View source code 6 votes vote down vote up
/**
 * @test java.util.regex.Matcher#hasAnchoringBounds()
 * test hasAnchoringBounds() method.
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "Verifies that hasAnchoringBounds method returns correct value.",
    method = "hasAnchoringBounds",
    args = {}
)          
 */
public void test_hasAnchoringBounds() {
    String testPattern = "abb";
    String testString = "abb";
    Pattern pat = Pattern.compile(testPattern);
    Matcher mat = pat.matcher(testString);

    assertTrue("Matcher uses anchoring bound by default",
            mat.hasAnchoringBounds());

    Matcher mu = mat.useAnchoringBounds(true);
    assertTrue("Incorrect value of anchoring bounds",
            mu.hasAnchoringBounds());

    mu = mat.useAnchoringBounds(false);
    assertFalse("Incorrect value of anchoring bounds",
            mu.hasAnchoringBounds());
}