Run a provided "matcher" function but reset the current position afterwards. Fatal failure of the matcher is not suppressed.
422762
function (scanner, matcher) {
  var start = scanner.pos;
  var result = matcher(scanner);
  scanner.pos = start;
  return result;
}
1223306
public int matches(Replaceable text,
                       int[] offset,
                       int limit,
                       boolean incremental) {
        int start = offset[0];
        int count = 0;
        while (count < maxCount) {
            int pos = offset[0];
            int m = matcher.matches(text, offset, limit, incremental);
            if (m == U_MATCH) {
                ++count;
                if (pos == offset[0]) {
                    // If offset has not moved we have a zero-width match.
                    // Don't keep matching it infinitely.
                    break;
                }
            } else if (incremental && m == U_PARTIAL_MATCH) {
                return U_PARTIAL_MATCH;
            } else {
                break;
            }
        }
        if (incremental && offset[0] == limit) {
            return U_PARTIAL_MATCH;
        }
        if (count >= minCount) {
            return U_MATCH;
        }
        offset[0] = start;
        return U_MISMATCH;
    }
194401
def restart(self, offset: int):
        '''
        '''
        yield from self._control_stream.write_command(Command('REST', str(offset)))

        reply = yield from self._control_stream.read_reply()

        self.raise_if_not_match('Restart', ReplyCodes.requested_file_action_pending_further_information, reply)
654304
static Matcher removeStartFollowedByMatchAny(Matcher matcher) {
    if (matcher instanceof SeqMatcher) {
      List<Matcher> matchers = matcher.<SeqMatcher>as().matchers();
      if (matchers.size() == 2
          && matchers.get(0) instanceof StartMatcher
          && matchers.get(1) instanceof ZeroOrMoreMatcher) {
        ZeroOrMoreMatcher zm = matchers.get(1).as();
        if (zm.repeated() instanceof AnyMatcher) {
          return zm;
        }
      }
    }
    return matcher;
  }
763689
function hasAncestor(node, matcher) {
        while ( (node = node.parentNode) ) {
            if (matcher(node)) {
                return true;
            }
        }
        return false;
    }
419302
def run(self, matches):
        
        def _run(matches):
            group_starting_pos = 0
            for current_pos, (group_length, group_function) in enumerate(zip(self.group_lengths, self.group_functions)):
                start_pos = current_pos + group_starting_pos
                end_pos = current_pos + group_starting_pos + group_length
                yield group_function(matches[start_pos:end_pos])
                group_starting_pos += group_length - 1
        return self.final_function(list(_run(matches)))
316048
def __create_matcher(self, match_class, **keywds):
        """"""
        matcher_args = keywds.copy()
        del matcher_args['function']
        del matcher_args['recursive']
        if 'allow_empty' in matcher_args:
            del matcher_args['allow_empty']

        decl_matcher = decl_matcher = match_class(**matcher_args)
        if keywds['function']:
            self._logger.debug(
                'running query: %s and <user defined function>',
                str(decl_matcher))
            return lambda decl: decl_matcher(decl) and keywds['function'](decl)

        self._logger.debug('running query: %s', str(decl_matcher))
        return decl_matcher
687832
void handleRemove(SimpleTest test, Conjunction selector,
                    MatchTarget object, InternTable subExpr, OrdinalPosition parentId) throws MatchingException
  {
    if (tc.isEntryEnabled())
	  tc.entry(this,cclass, "handleRemove", new Object[]{test,selector,object,subExpr});
	    	
    // The following returns the comparand if test is an equality test, null otherwise
    Object value = test.getValue();
    if (value != null)
      handleEqualityRemove(new Wrapper(value), selector, object, subExpr, parentId);
    else {
      // Inequality or range, was in CheapRangeTable
      ContentMatcher next = (ContentMatcher) ranges.getExact(test);
      // Delete the subscription, also deleting a Matcher if called for and replacing with
      // descendent or null
      ContentMatcher newNext = (ContentMatcher) next.remove(selector,
        object, subExpr, ordinalPosition);
      // See if Matcher was replaced or removed, and reflect that change in the right place
      if (newNext != next)
        if (newNext != null)
          ranges.replace(test, newNext);
        else
          ranges.remove(test);
    }
    if (tc.isEntryEnabled())
	  tc.exit(this,cclass, "handleRemove");          
  }
1258296
def _match_iter_generic(self, path_elements, start_at):
        """"""

        length = len(path_elements)
        # If bound to start, we stop searching at the first element
        if self.bound_start:
            end = 1
        else:
            end = length - self.length + 1

        # If bound to end, we start searching as late as possible
        if self.bound_end:
            start = length - self.length
        else:
            start = start_at

        if start > end or start < start_at or end > length - self.length + 1:
            # It's impossible to match. Either
            # 1) the search has a fixed start and end, and path_elements
            #    does not have enough elements for a match, or
            # 2) To match the bound_end, we have to start before the start_at,
            #    which means the search is impossible
            # 3) The end is after the last possible end point in path_elements
            return

        for index in range(start, end):
            matched = True
            i = index
            for matcher in self.elements:
                element = path_elements[i]
                i += 1
                if not matcher.match(element):
                    matched = False
                    break
            if matched:
                yield index + self.length
396770
function rangeFromMatch(match) {
        var wrappers = getWrappersByIndex(indexOf(match));

        var rng = editor.dom.createRng();
        rng.setStartBefore(wrappers[0]);
        rng.setEndAfter(wrappers[wrappers.length - 1]);

        return rng;
      }
466376
def remove(self, matcher, obj):
        '''
        
        '''
        current = self.subtree(matcher, False)
        if current is None:
            return
        # Assume that this pair only appears once
        if current._use_dict:
            try:
                del current.matchers_dict[(obj, matcher)]
            except KeyError:
                pass
        else:
            if len(current.matchers_list) > 10:
                # Convert to dict
                current.matchers_dict = OrderedDict((v, None) for v in current.matchers_list
                                                    if v != (obj, matcher))
                current.matchers_list = None
                current._use_dict = True
            else:
                try:
                    current.matchers_list.remove((obj, matcher))
                except ValueError:
                    pass
        while ((not current.matchers_dict) if current._use_dict
               else (not current.matchers_list))\
                and not current.matchers_dict\
                and not hasattr(current,'any')\
                and not current.index and current.parent is not None:
            # remove self from parents
            ind = current.parentIndex
            if ind is None:
                del current.parent.any
            else:
                del current.parent.index[ind]
            p = current.parent
            current.parent = None
            current = p
1004560
function handle(match, position, parent, phrase) {
        var index = list.indexOf(phrase)
        var pattern = byIndex[index]
        var id = pattern.id

        if (!(id in matches)) {
          matches[id] = []
        }

        matches[id].push({
          type: pattern.inconsiderate[phrase],
          parent: parent,
          nodes: match,
          start: position,
          end: position + match.length - 1
        })
      }
842869
def repl(optimize=True, persist=True):
    
    print("Extra commands for the REPL:")
    print(".code    - print code")
    print(".raw     - print raw code")
    print(".quit    - exit immediately")
    print(".reset   - reset machine (IP and stacks)")
    print(".restart - create a clean, new machine")
    print(".clear   - same as .restart")
    print(".stack   - print data stack")
    print("")

    machine = Machine([])

    def match(s, *args):
        return any(map(lambda arg: s.strip()==arg, args))

    while True:
        try:
            source = raw_input("> ").strip()

            if source[0] == "." and len(source) > 1:
                if match(source, ".quit"):
                    return
                elif match(source, ".code"):
                    print_code(machine)
                elif match(source, ".raw"):
                    print(machine.code)
                elif match(source, ".reset"):
                    machine.reset()
                elif match(source, ".restart", ".clear"):
                    machine = Machine([])
                elif match(source, ".stack"):
                    print(machine.stack)
                else:
                    raise ParseError("Unknown command: %s" % source)
                continue

            code = compile(parse(source), silent=False, optimize=optimize)

            if not persist:
                machine.reset()

            machine.code += code
            machine.run()
        except EOFError:
            return
        except KeyboardInterrupt:
            return
        except ParseError as e:
            print("Parse error: %s" % e)
        except MachineError as e:
            print("Machine error: %s" % e)
        except CompileError as e:
            print("Compile error: %s" % e)
903575
function resetResolvedData(matcher) {
        matcher.resolvedMatches = null;
        matcher.resolvedMatchesObj = null;
        matcher.resolvedMatchesById = null;
        matcher.assignedIds = null;
        matcher.assignedIdsMap = null;
    }
1372558
private void handleMatch(Point match)
    {
        if (match == null)
        {
            int caretPosition = textComponent.getCaretPosition();
            Document document = textComponent.getDocument();
            caretPosition = Math.max(0, Math.min(
                document.getLength(), caretPosition));
            textComponent.setCaretPosition(caretPosition);
            textComponent.moveCaretPosition(caretPosition);
            textComponent.getCaret().setSelectionVisible(false);
        }
        else
        {
            textComponent.setCaretPosition(match.y);
            textComponent.moveCaretPosition(match.x);
            textComponent.getCaret().setSelectionVisible(true);
        }
    }
686754
@Override
    @Deprecated
    protected void handleTransliterate(Replaceable text,
                                       Position index, boolean incremental) {
        /* We keep start and limit fixed the entire time,
         * relative to the text -- limit may move numerically if text is
         * inserted or removed.  The cursor moves from start to limit, with
         * replacements happening under it.
         *
         * Example: rules 1. ab>x|y
         *                2. yc>z
         *
         * |eabcd   start - no match, advance cursor
         * e|abcd   match rule 1 - change text & adjust cursor
         * ex|ycd   match rule 2 - change text & adjust cursor
         * exz|d    no match, advance cursor
         * exzd|    done
         */

        /* A rule like
         *   a>b|a
         * creates an infinite loop. To prevent that, we put an arbitrary
         * limit on the number of iterations that we take, one that is
         * high enough that any reasonable rules are ok, but low enough to
         * prevent a server from hanging.  The limit is 16 times the
         * number of characters n, unless n is so large that 16n exceeds a
         * uint32_t.
         */
        synchronized(data)  {
            int loopCount = 0;
            int loopLimit = (index.limit - index.start) << 4;
            if (loopLimit < 0) {
                loopLimit = 0x7FFFFFFF;
            }

            while (index.start < index.limit &&
                    loopCount <= loopLimit &&
                    data.ruleSet.transliterate(text, index, incremental)) {
                ++loopCount;
            }
        }
    }
485785
def replace(self, html):
        """"""
        self.html = html
        text = html.text()
        positions = []

        def perform_replacement(match):
            offset = sum(positions)
            start, stop = match.start() + offset, match.end() + offset

            s = self.html[start:stop]
            if self._is_replacement_allowed(s):
                repl = match.expand(self.replacement)
                self.html[start:stop] = repl
            else:
                repl = match.group()  # no replacement takes place

            positions.append(match.end())
            return repl

        while True:
            if positions:
                text = text[positions[-1]:]

            text, n = self.pattern.subn(perform_replacement, text, count=1)
            if not n:  # all is already replaced
                break