Associates {@code rule} with {@code pattern}.
181033
@Requires({
    "isValidPattern(pattern)",
    "rule != null"
  })
  @Ensures({
    "rule.equals(get(pattern))",
    "!isOverriden(pattern)"
  })
  public void put(String pattern, R rule) {
    String canon = pattern.replace('/', '.');
    boolean exact = !canon.endsWith(".*");
    if (!exact) {
      canon = canon.substring(0, canon.length() - 2);
    }

    String[] parts = canon.split("\\.");

    TernaryNode current = root;
    TernaryNode parent = root;
    int parentIndex = -1;
    for (int i = 0; i < parts.length; ++i) {
      TernaryNode next = current.children.get(parts[i]);
      if (next == null) {
        next = new TernaryNode(null, false);
        current.children.put(parts[i], next);
      }
      if (next.rule != null && !next.exact) {
        parent = next;
        parentIndex = i;
      }
      current = next;
    }

    if (!exact) {
      /* Override patterns beginning with this one. */
      current.children.clear();
    }

    if (!rule.equals(parent.rule)) {
      current.rule = rule;
      current.exact = exact;
    } else {
      /*
       * The new rule we are inserting is already specified through
       * inheritance. Remove spurious nodes. This ensures that any
       * overriding branch is meaningful; that is, it specifies a rule
       * value different from the inherited one.
       */
      current = parent;
      for (int i = parentIndex + 1; i < parts.length; ++i) {
        TernaryNode next = current.children.get(parts[i]);
        if (next.rule == null) {
          current.children.remove(parts[i]);
          break;
        }
      }
    }
  }
902131
public CharSequence matchesPattern(final CharSequence input, final String pattern, final String message) {
        if (!Pattern.matches(pattern, input)) {
            fail(message);
        }
        return input;
    }
995272
public static final String convertPattern(String pattern) {
        if (pattern == null) {
            return null;
        }
        else {
            String convertedPattern = pattern;
            for (PatternConverter converter : PATTERN_CONVERTERS) {
                convertedPattern = converter.convert(convertedPattern);
            }

            return convertedPattern;
        }
    }
1172877
public static SimonPattern create(String pattern) {
		if (pattern == null) {
			return null;
		}

		return createForType(pattern, Simon.class);
	}
1104566
def addpattern(base_func):
    """"""
    def pattern_adder(func):
        @_coconut.functools.wraps(func)
        @_coconut_tco
        def add_pattern_func(*args, **kwargs):
            try:
                return base_func(*args, **kwargs)
            except _coconut_MatchError:
                raise _coconut_tail_call(func, *args, **kwargs)
        return add_pattern_func
    return pattern_adder
650601
private final boolean matchPattern(byte[][] patterns, int bufferIndex)
   {
      boolean match = false;
      for (byte[] pattern : patterns)
      {
         int index = 0;
         match = true;
         for (byte b : pattern)
         {
            if (b != m_buffer[bufferIndex + index])
            {
               match = false;
               break;
            }
            ++index;
         }
         if (match)
         {
            break;
         }
      }
      return match;
   }
889072
def add(self, rule, method, target, name=None):
        '''  '''
        if rule in self.rules:
            self.rules[rule][method] = target
            if name: self.builder[name] = self.builder[rule]
            return

        target = self.rules[rule] = {method: target}

        # Build pattern and other structures for dynamic routes
        anons = 0      # Number of anonymous wildcards
        pattern = ''   # Regular expression  pattern
        filters = []   # Lists of wildcard input filters
        builder = []   # Data structure for the URL builder
        is_static = True
        for key, mode, conf in self.parse_rule(rule):
            if mode:
                is_static = False
                mask, in_filter, out_filter = self.filters[mode](conf)
                if key:
                    pattern += '(?P<%s>%s)' % (key, mask)
                else:
                    pattern += '(?:%s)' % mask
                    key = 'anon%d' % anons; anons += 1
                if in_filter: filters.append((key, in_filter))
                builder.append((key, out_filter or str))
            elif key:
                pattern += re.escape(key)
                builder.append((None, key))
        self.builder[rule] = builder
        if name: self.builder[name] = builder

        if is_static and not self.strict_order:
            self.static[self.build(rule)] = target
            return

        def fpat_sub(m):
            return m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:'
        flat_pattern = re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', fpat_sub, pattern)

        try:
            re_match = re.compile('^(%s)$' % pattern).match
        except re.error, e:
            raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, e))

        def match(path):
            """ Return an url-argument dictionary. """
            url_args = re_match(path).groupdict()
            for name, wildcard_filter in filters:
                try:
                    url_args[name] = wildcard_filter(url_args[name])
                except ValueError:
                    raise HTTPError(400, 'Path has wrong format.')
            return url_args

        try:
            combined = '%s|(^%s$)' % (self.dynamic[-1][0].pattern, flat_pattern)
            self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1])
            self.dynamic[-1][1].append((match, target))
        except (AssertionError, IndexError), e: # AssertionError: Too many groups
            self.dynamic.append((re.compile('(^%s$)' % flat_pattern),
                                [(match, target)]))
        return match
598421
@Override
    public final void applyPattern(String pattern)
    {

        if (hasRegistry())
        {
            super.applyPattern(pattern);
            toPattern = super.toPattern();
            return;
        }

        ArrayList<Format> foundFormats = new ArrayList<Format>();
        ArrayList<String> foundDescriptions = new ArrayList<String>();
        StringBuilder stripCustom = new StringBuilder(pattern.length());

        ParsePosition pos = new ParsePosition(0);
        char[] c = pattern.toCharArray();
        int fmtCount = 0;

        while (pos.getIndex() < pattern.length())
        {

            char charType = c[pos.getIndex()];

            if (QUOTE == charType)
            {

                appendQuotedString(pattern, pos, stripCustom, true);
                continue;

            }

            if (START_FE == charType)
            {

                fmtCount++;
                seekNonWs(pattern, pos);
                int start = pos.getIndex();
                int index = readArgumentIndex(pattern, next(pos));
                stripCustom.append(START_FE).append(index);
                seekNonWs(pattern, pos);
                Format format = null;
                String formatDescription = null;
                if (c[pos.getIndex()] == START_FMT)
                {
                    formatDescription = parseFormatDescription(pattern, next(pos));
                    format = getFormat(formatDescription);
                    if (format == null)
                    {
                        stripCustom.append(START_FMT).append(formatDescription);
                    }
                }
                foundFormats.add(format);
                foundDescriptions.add(format == null ? null : formatDescription);

                Preconditions.checkState(foundFormats.size() == fmtCount);
                Preconditions.checkState(foundDescriptions.size() == fmtCount);

                if (c[pos.getIndex()] != END_FE)
                {
                    throw new IllegalArgumentException("Unreadable format element at position " + start);
                }

            }

            //$FALL-THROUGH$
            stripCustom.append(c[pos.getIndex()]);
            next(pos);

        }

        super.applyPattern(stripCustom.toString());

        toPattern = insertFormats(super.toPattern(), foundDescriptions);

        if (containsElements(foundFormats))
        {
            Format[] origFormats = getFormats();
            // only loop over what we know we have, as MessageFormat on Java 1.3
            // seems to provide an extra format element:
            Iterator<Format> it = foundFormats.iterator();
            for (int i = 0; it.hasNext(); i++)
            {
                Format f = it.next();
                if (f != null)
                {
                    origFormats[i] = f;
                }
            }
            super.setFormats(origFormats);
        }

    }
696481
public void compile(String pattern) {
		this.expandedPattern = expand(pattern);
		
		// Compile the regex
		if (!expandedPattern.isEmpty()) {
			regexp = Pattern.compile(expandedPattern);
		} else {
			throw new IllegalArgumentException("Pattern is not found '"
					+ pattern + "'");
		}
	}
770601
private Pattern getPattern(String expr)
    {
        Pattern pattern = patterns.get(expr);
        if(pattern == null)
        {
            pattern = Pattern.compile(expr);
            patterns.put(expr, pattern);
        }
        return pattern;
    }
1123757
private void simplify(PatternRule rule, List<String> xmlLines) {
    List<Integer> linesToRemove = new ArrayList<>();
    String currentRuleId = null;
    Pattern pattern = Pattern.compile(".*id=[\"'](.*?)[\"'].*");
    String expectedSubId = rule.getSubId();
    int lineCount = 0;
    int subRuleCount = 0;
    int removedCount = 0;
    boolean inRuleGroup = false;
    String newRegex = null;
    boolean inAntiPattern = false;
    for (lineCount = 0; lineCount < xmlLines.size(); lineCount++) {
    //for (String xmlLine : xmlLines) {
      String xmlLine = xmlLines.get(lineCount);
      if (xmlLine.contains("<rulegroup")) {
        subRuleCount = 0;
        inRuleGroup = true;
      } else if (xmlLine.contains("</rulegroup>")) {
        subRuleCount = 0;
        inRuleGroup = false;
      } else if ((xmlLine.contains("<rule ")||xmlLine.contains("<rule>")) && inRuleGroup) {
        subRuleCount++;
      }
      Matcher m = pattern.matcher(xmlLine);
      if (m.matches()) {
        currentRuleId = m.group(1);
      }
      if (currentRuleId != null && !currentRuleId.equals(rule.getId())) {
        continue;
      }
      if (!inRuleGroup) {
        subRuleCount = 1;
      }
      if (!expectedSubId.equals("0") && !expectedSubId.equals(String.valueOf(subRuleCount))) {
        continue;
      }
      if (xmlLine.matches(".*<antipattern.*")) {
        inAntiPattern = true;
      }
      if (inAntiPattern) {
        continue;
      }
      if (xmlLine.matches(".*</antipattern.*")) {
        inAntiPattern = false;
        continue;
      }
      if (xmlLine.matches(".*<(token|pattern).*") || xmlLine.matches("\\s*</?marker>.*")) {
        linesToRemove.add(lineCount);
      }
      if (xmlLine.matches(".*</pattern.*")) {
        linesToRemove.add(lineCount);
        int lastTokenIndent = xmlLine.indexOf("<");
        newRegex = Strings.repeat(" ", lastTokenIndent) + getRegex(rule);
      }
    }
    Collections.reverse(linesToRemove); // start from end, as we need to remove items
    for (Integer s : linesToRemove) {
      xmlLines.remove(s.intValue());
      removedCount++;
    }
    if (removedCount == 0) {
      System.err.println("No line removed: " + rule + "[" + expectedSubId + "]");
    } else {
      xmlLines.add(linesToRemove.get(linesToRemove.size()-1), newRegex);
      touchedRulesCount++;
    }
  }
972713
public static boolean match(WildcardPattern[] patterns, String value) {
    for (WildcardPattern pattern : patterns) {
      if (pattern.match(value)) {
        return true;
      }
    }
    return false;
  }
1368126
public static Matcher<String> containsPatterns(String... patterns) {
        List<Matcher<? super String>> matchers = new ArrayList<Matcher<? super String>>();
        for (String pattern : patterns) {
            matchers.add(pattern(pattern));
        }
        return allOf(matchers);
    }
157866
protected static Assignment findAssignmentFromTerminalPattern(EObject rule, String pattern) {
		return IterableExtensions.findFirst(GrammarUtil.containedAssignments(rule),
				assignment -> nameMatches(assignment.getTerminal(), pattern));
	}
1240799
private static boolean doesNameMatchPattern(final Principal principal, final Pattern pattern) {
        if (pattern != null) {
            val name = principal.getName();
            val result = pattern.matcher(name).matches();
            LOGGER.debug("[{}] matches [{}] == [{}]", pattern.pattern(), name, result);
            return result;
        }
        return true;
    }
1280621
public static CharSequence matchesPattern(final CharSequence input, final String pattern, final String message) {
        return INSTANCE.matchesPattern(input, pattern, message);
    }
513939
def _compile_pattern(self, rule):
        '''  '''
        out = ''
        for i, part in enumerate(self.syntax.split(rule)):
            if i%3 == 0:   out += re.escape(part.replace('\\:',':'))
            elif i%3 == 1: out += '(?P<%s>' % part if part else '(?:'
            else:          out += '%s)' % (part or '[^/]+')
        return re.compile('^%s$'%out)