Java Code Examples for java.util.regex.Pattern

The following are top voted examples for showing how to use java.util.regex.Pattern. 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: CorePropertiesPageletAdaptor.java View source code 7 votes vote down vote up
/**
 * Checks if the characters in the String s conform to the regex specified.
 * 
 * @param s
 * @param regex
 * @return
 */
private boolean isValidFormat(String s, String regex) {
	char[] array = s.toCharArray();
	boolean matches = true;
	for (int i = 0; i < array.length; i++) {
		if (!Pattern.matches(regex, String.valueOf(array[i]))) {
			matches = false;
			break;
		}
	}
	return matches;
}
 
Example 2
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 3
Project: lettuce   File: ServerCommandTest.java View source code 6 votes vote down vote up
@Test
public void clientKill() throws Exception {
    Pattern p = Pattern.compile(".*addr=([^ ]+).*");
    String clients = redis.clientList();
    Matcher m = p.matcher(clients);

    assertThat(m.lookingAt()).isTrue();
    assertThat(redis.clientKill(m.group(1))).isEqualTo("OK");
}
 
Example 4
Project: adc-wildner   File: Dataset.java View source code 6 votes vote down vote up
/**
 * Create a transaction object from a line from the input file
 * @param line a line from input file
 * @return a transaction
 */
private Transaction createTransaction(String line) {

    //build the items
    Pattern splitPattern = Pattern.compile(" ");
    String[] items = splitPattern.split(line);

    Integer[] itemsSorted = new  Integer[items.length];

    for (int i = 0; i < items.length; i++) {
    	Integer item = Integer.valueOf(items[i]);
    	itemsSorted[i] = item;

        uniqueItems.add(item);
    }

    // update max item by checking the last item of the transaction
    int lastItem = itemsSorted[itemsSorted.length - 1];
    if(lastItem > maxItem) {
        maxItem = lastItem;
    }
    return new Transaction(itemsSorted);
}
 
Example 5
Project: netlib   File: Condition.java View source code 6 votes vote down vote up
/**
 * Create a condition that exactly maps the provided TCP/IP address/name/port to the provided NetLayer.
 * 
 * @param tcpipNetAddress
 * @param netLayer
 */
public Condition(TcpipNetAddress tcpipNetAddress, NetLayer netLayer) {
    this(Pattern.compile(
            "^"+ 
            "(("+Pattern.quote(tcpipNetAddress.getIpaddressAndPort()) + ")|"+
            " ("+Pattern.quote(tcpipNetAddress.getHostnameAndPort()) + "))"+
            "$"),
         netLayer);
}
 
Example 6
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 7
Project: jena   File: RegexJava.java View source code 6 votes vote down vote up
public static int makeMask(String modifiers)
{
    if ( modifiers == null )
        return 0 ;
    
    int newMask = 0 ;
    for ( int i = 0 ; i < modifiers.length() ; i++ )
    {
        switch(modifiers.charAt(i))
        {
            //case 'i' : newMask |= Pattern.CASE_INSENSITIVE;     break ;
            case 'i' : 
                // Need both (Java 1.4)
                newMask |= Pattern.UNICODE_CASE ;
                newMask |= Pattern.CASE_INSENSITIVE;
                break ;
            case 'm' : newMask |= Pattern.MULTILINE ;           break ;
            case 's' : newMask |= Pattern.DOTALL ;              break ;
            //case 'x' : newMask |= Pattern.;  break ;
            
            default  : 
                throw new QueryParseException("Illegal flag in regex modifiers: "+modifiers.charAt(i), -1, -1) ;
        }
    }
    return newMask ;
}
 
Example 8
Project: torodb   File: BasicQueryTranslator.java View source code 6 votes vote down vote up
private QueryCriteria translateRegexOperand(
        @Nonnull AttributeReference attRefAcum,
        @Nonnull Object uncastedArg,
        @Nonnull ExpModifications modifications) {
    String pattern;
    int flags;
    if (uncastedArg instanceof String) {
        pattern = (String) uncastedArg;
        flags = 0;
    }
    else if (uncastedArg instanceof Pattern) {
        Pattern arg = (Pattern) uncastedArg;
        pattern = arg.pattern();
        flags = arg.flags();
    }
    else {
        throw new UserToroException("$regex has to be a string or a pattern");
    }
    
    Pattern regex;
    RegexExpModifier modifier = modifications.consumeModifier(RegexExpModifier.class);
    if (modifier != null) {
        regex = Pattern.compile(pattern, flags | modifier.toPatternFlags());
    }
    else {
        regex = Pattern.compile(pattern, flags);
    }
    return new MatchPatternQueryCriteria(attRefAcum, new PatternValue(regex));
}
 
Example 9
Project: ISAcreator   File: AddStudyDialog.java View source code 6 votes vote down vote up
private boolean isValidName(String text) {
    Pattern pattern = Pattern.compile(
            "# Match a valid Windows filename (unspecified file system).          \n" +
                    "^                                # Anchor to start of string.        \n" +
                    "(?!                              # Assert filename is not: CON, PRN, \n" +
                    "  (?:                            # AUX, NUL, COM1, COM2, COM3, COM4, \n" +
                    "    CON|PRN|AUX|NUL|             # COM5, COM6, COM7, COM8, COM9,     \n" +
                    "    COM[1-9]|LPT[1-9]            # LPT1, LPT2, LPT3, LPT4, LPT5,     \n" +
                    "  )                              # LPT6, LPT7, LPT8, and LPT9...     \n" +
                    "  (?:\\.[^.]*)?                  # followed by optional extension    \n" +
                    "  $                              # and end of string                 \n" +
                    ")                                # End negative lookahead assertion. \n" +
                    "[^<>:\"/\\\\|?*\\x00-\\x1F]*     # Zero or more valid filename chars.\n" +
                    "[^<>:\"/\\\\|?*\\x00-\\x1F\\ .]  # Last char is not a space or dot.  \n" +
                    "$                                # Anchor to end of string.            ",
            Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS);
    Matcher matcher = pattern.matcher(text);
    return matcher.matches();
}
 
Example 10
Project: jlibs   File: Navigator2.java View source code 6 votes vote down vote up
public E resolve(E node, String path, Convertor<E, String> convertor, String separator){
    if(path.equals("."))
        return node;

    String tokens[] = Pattern.compile(separator, Pattern.LITERAL).split(path);
    for(String token: tokens){
        if(token.equals("..")){
            node = parent(node);
            continue;
        }
        int predicate = 1;
        int openBrace = token.lastIndexOf('[');
        if(openBrace!=-1){
            predicate = Integer.parseInt(token.substring(openBrace+1, token.length()-1));
            token = token.substring(0, openBrace);
        }

        Sequence<? extends E> children = children(node);
        while(children.hasNext()){
            E child = children.next();
            if(token.equals(convertor.convert(child))){
                if(predicate==1){
                    node = child;
                    break;
                }else
                    predicate--;
            }
        }
    }
    return null;
}
 
Example 11
Project: netlib   File: RendezvousServiceDescriptorLocalTest.java View source code 6 votes vote down vote up
@Test
public void testFormatRendezvousServiceDescriptor() throws Exception {
    // read and parse
    String rendezvousServiceDescriptorStr = FileUtil.getInstance().readFileFromClasspath(EXAMPLE_RENDEZVOUS_SERVICE_DESCRIPTOR_PATH);
    RendezvousServiceDescriptor sd = new RendezvousServiceDescriptor(rendezvousServiceDescriptorStr, EXAMPLE_SD_VALID_DATE);
    // check basics
    assertEquals("wrong z", "duskgytldkxiuqc6", sd.getZ());
    

    // check formatting
    String reformattedRendezvousServiceDescriptorStr = sd.toServiceDescriptorString();
    log.info("reformattedRendezvousServiceDescriptorStr=\n"+reformattedRendezvousServiceDescriptorStr);
    
    // check - but without signature (because the signature cannot be created here because of this missing private key)
    String expextedRendezvousServiceDescriptorStr = 
        Pattern.compile("-----BEGIN SIGNATURE-----.*-----END SIGNATURE-----",
                Pattern.DOTALL + Pattern.MULTILINE + Pattern.CASE_INSENSITIVE + Pattern.UNIX_LINES).
        matcher(rendezvousServiceDescriptorStr).
        replaceAll("-----BEGIN SIGNATURE-----\n-----END SIGNATURE-----");
    log.info("expextedRendezvousServiceDescriptorStr="+expextedRendezvousServiceDescriptorStr);
    assertEquals("wrong reformatted RendezvousServiceDescriptorStr",
            expextedRendezvousServiceDescriptorStr,
            reformattedRendezvousServiceDescriptorStr);
}
 
Example 12
Project: k3po   File: NamedGroupPattern.java View source code 6 votes vote down vote up
NamedGroupPattern(Pattern pattern, List<String> groupNames) {
    this.pattern = pattern;
    this.groupNames = groupNames;
    int groupNamesSize = groupNames.size();
    if (groupNamesSize != 0 && (pattern.matcher("").groupCount() != groupNamesSize)) {
        throw new PatternSyntaxException(
                "Inconsistant named group count. The number of named groups must match the number of groups in the pattern.",
                pattern.toString(), -1);
    }
}
 
Example 13
Project: torodb   File: PatternValue.java View source code 6 votes vote down vote up
private String toEmbeddedFlags() {
    int flags = pattern.flags();
    if (flags == 0) {
        return "";
    }
    
    StringBuilder sb = new StringBuilder(30);
    sb.append("(?");
    if ((flags & Pattern.CANON_EQ) != 0) {
        throw new IllegalStateException("The flag CANON_EQ cannot be serialized as string");
    }
    if ((flags & Pattern.LITERAL) != 0) {
        throw new IllegalStateException("The flag LITERAL cannot be serialized as string");
    }
    if ((flags & Pattern.CASE_INSENSITIVE) != 0) {
        sb.append('i');
    }
    if ((flags & Pattern.COMMENTS) != 0) {
        sb.append('x');
    }
    if ((flags & Pattern.MULTILINE) != 0) {
        sb.append('m');
    }
    if ((flags & Pattern.DOTALL) != 0) {
        sb.append('s');
    }
    if ((flags & Pattern.UNICODE_CASE) != 0) {
        sb.append('u');
    }
    if ((flags & Pattern.UNIX_LINES) != 0) {
        sb.append('d');
    }
    sb.append(')');
    
    return sb.toString();
}