Steps through the target node, looking for matches, and
calling replaceFn when a match is found.
515119
function() {

      var matches = this.matches
      var node = this.node
      var elementFilter = this.options.filterElements
      var startPortion,
        endPortion,
        innerPortions = [],
        curNode = node,
        match = matches.shift(),
        atIndex = 0, // i.e. nodeAtIndex
        matchIndex = 0,
        portionIndex = 0,
        doAvoidNode,
        nodeStack = [node]
      out: while (true) {

        if (curNode.nodeType === 3) {

          if (!endPortion && curNode.length + atIndex >= match.endIndex) {

            // We've found the ending
            endPortion = {
              node: curNode,
              index: portionIndex++,
              text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex),
              indexInMatch: atIndex - match.startIndex,
              indexInNode: match.startIndex - atIndex, // always zero for end-portions
              endIndexInNode: match.endIndex - atIndex,
              isEnd: true
            }
          } else if (startPortion) {
            // Intersecting node
            innerPortions.push({
              node: curNode,
              index: portionIndex++,
              text: curNode.data,
              indexInMatch: atIndex - match.startIndex,
              indexInNode: 0 // always zero for inner-portions
            })
          }

          if (!startPortion && curNode.length + atIndex > match.startIndex) {
            // We've found the match start
            startPortion = {
              node: curNode,
              index: portionIndex++,
              indexInMatch: 0,
              indexInNode: match.startIndex - atIndex,
              endIndexInNode: match.endIndex - atIndex,
              text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex)
            }
          }

          atIndex += curNode.data.length
        }

        doAvoidNode = curNode.nodeType === 1 && elementFilter && !elementFilter(curNode)
        if (startPortion && endPortion) {

          curNode = this.replaceMatch(match, startPortion, innerPortions, endPortion)
          // processMatches has to return the node that replaced the endNode
          // and then we step back so we can continue from the end of the 
          // match:

          atIndex -= (endPortion.node.data.length - endPortion.endIndexInNode)
          startPortion = null
          endPortion = null
          innerPortions = []
          match = matches.shift()
          portionIndex = 0
          matchIndex++
          if (!match) {
            break; // no more matches
          }

        } else if (
          !doAvoidNode &&
          (curNode.firstChild || curNode.nextSibling)
        ) {
          // Move down or forward:
          if (curNode.firstChild) {
            nodeStack.push(curNode)
            curNode = curNode.firstChild
          } else {
            curNode = curNode.nextSibling
          }
          continue
        }

        // Move forward or up:
        while (true) {
          if (curNode.nextSibling) {
            curNode = curNode.nextSibling
            break
          }
          curNode = nodeStack.pop()
          if (curNode === node) {
            break out
          }
        }

      }

    }
797439
function attemptReplacePatterns(token, replacements, measureThreshold) {
  var replacement = null;

  for(var i = 0; i < replacements.length; i++) {
    if(!measureThreshold || measure(attemptReplace(token, replacements[i][0], '')) > measureThreshold)
      replacement = attemptReplace(token, replacements[i][0], replacements[i][1]);

    if(replacement)
      break;
  }

  return replacement;
}
452797
def replace_string_node(target, value)
      quote = target.loc.begin.source
      rewriter.replace(target.loc.expression, "#{quote}#{value}#{quote}")
    end
72419
function replaceNode(node, newCode) {
        code = code.substr(0,node.start) + newCode + code.substr(node.end);
        var offs = newCode.length - (node.end-node.start); // offset for future code snippets
        for (var i in tasks)
          if (tasks[i].node.start > node.start) {
            tasks[i].node.start += offs;
            tasks[i].node.end += offs;
          }
      }
954461
function processTag(tag, targets) {
  if (tag.description) {
    tag.description = replaceLink(tag.description, targets);
  }
  if (tag.params) {
    tag.params.forEach(function (param) {
      if (param.description) {
        param.description = replaceLink(param.description, targets);
      }
    });
  }
  if (tag.members) {
    tag.members.forEach(function (member) {
      processTag(member, targets);
    });
  }
  if (tag.methods) {
    tag.methods.forEach(function (method) {
      processTag(method, targets);
    });
  }
}
386585
def _first_step_to_match(match_step):
    """"""
    parts = []

    if match_step.root_block is not None:
        if not isinstance(match_step.root_block, QueryRoot):
            raise AssertionError(u'Expected None or QueryRoot root block, received: '
                                 u'{} {}'.format(match_step.root_block, match_step))

        match_step.root_block.validate()

        start_class = get_only_element_from_collection(match_step.root_block.start_class)
        parts.append(u'class: %s' % (start_class,))

    # MATCH steps with a QueryRoot root block shouldn't have a 'coerce_type_block'.
    if match_step.coerce_type_block is not None:
        raise AssertionError(u'Invalid MATCH step: {}'.format(match_step))

    if match_step.where_block:
        match_step.where_block.validate()
        parts.append(u'where: (%s)' % (match_step.where_block.predicate.to_match(),))

    if match_step.as_block is None:
        raise AssertionError(u'Found a MATCH step without a corresponding Location. '
                             u'This should never happen: {}'.format(match_step))
    else:
        match_step.as_block.validate()
        parts.append(u'as: %s' % (_get_vertex_location_name(match_step.as_block.location),))

    return u'{{ %s }}' % (u', '.join(parts),)
1330909
function replacementForNode (node) {
  var rule = this.rules.forNode(node)
  var content = process.call(this, node)
  var whitespace = node.flankingWhitespace
  if (whitespace.leading || whitespace.trailing) content = content.trim()
  return (
    whitespace.leading +
    rule.replacement(content, node, this.options) +
    whitespace.trailing
  )
}
116716
public void doMatch() {
    boolean matchFound = false;
    for (ConsumablePattern<T> pattern : patterns) {
      if (pattern.matches(value)) {
        pattern.consume(value);
        matchFound = true;
        break;
      }
    }

    if (!matchFound) {
      throw new MatchException("No match found for " + value);
    }
  }
884804
function _makeFindCondition(match) {
        switch (typeof match) {
        case "function":
            return match;
        case "string":
            return function findCondition(name, node) {
                return node.name === name;
            }.bind(undefined, match.toUpperCase());
        case "number":
            return function findCondition(type, node) {
                return node.type === type;
            }.bind(undefined, match);
        default:
            console.error("Invalid find condition: " + match);
        }
    }
751776
def replace(self, new_node):
        """"""
        cur_node = self.cur_node
        nodestack = self.nodestack
        cur = nodestack.pop()
        prev = nodestack[-1]
        index = prev[-1] - 1
        oldnode, name = prev[-2][index]
        assert cur[0] is cur_node is oldnode, (cur[0], cur_node, prev[-2],
                                               index)
        parent = prev[0]
        if isinstance(parent, list):
            parent[index] = new_node
        else:
            setattr(parent, name, new_node)
412249
def replace(self, nodes):
        

        files = {}
        for node in nodes:
            if node.family == "SearchFile":
                files[node.file] = node.children
            elif node.family == "SearchOccurence":
                file = node.parent.file
                if not file in files:
                    files[file] = []
                files[file].append(node)

        replacement_pattern = self.Replace_With_comboBox.currentText()
        SearchAndReplace.insert_pattern(replacement_pattern, self.__replace_with_patterns_model)

        replace_results = {}
        for file, occurrences in files.iteritems():
            editor = self.__container.get_editor(file)
            if editor:
                document = editor.document()
            else:
                cache_data = self.__files_cache.get_content(file)
                if cache_data is None:
                    LOGGER.warning(
                        "!> {0} | '{1}' file doesn't exists in files cache!".format(self.__class__.__name__, file))
                    continue

                content = self.__files_cache.get_content(file).content
                document = self.__get_document(content)
                self.__cache(file, content, document)
            replace_results[file] = self.__replace_within_document(document, occurrences, replacement_pattern)

        self.set_replace_results(replace_results)
        self.__container.engine.notifications_manager.notify(
            "{0} | '{1}' pattern occurence(s) replaced in '{2}' files!".format(self.__class__.__name__,
                                                                               sum(replace_results.values()),
                                                                               len(replace_results.keys())))
440409
private void doProcessNext()
	{
		int _position = getPosition();
		Node _current = getSource().item(_position);

		if (getActionPool().containsKey(_current.getNodeName()))
		{
			getActionPool().get(_current.getNodeName()).execute(_current, _position);
		}
		else if (getActionPool().containsKey(NODE_NAME__DEFAULT))
		{
			getActionPool().get(NODE_NAME__DEFAULT).execute(_current, _position);
		}
		// else do nothing...

		// done
		_position++;
		setPosition(_position);
	}
931033
function nodeMatchesToken(node, token, root) {
  if (node === null || typeof node === 'string') {
    return false;
  }
  switch (token.type) {
    /**
     * Match every node
     * @example '*' matches every node
     */
    case UNIVERSAL_SELECTOR:
      return true;
    /**
     * Match against the className prop
     * @example '.active' matches <div className='active' />
     */
    case CLASS_SELECTOR:
      return hasClassName(node, token.name);
    /**
     * Simple type matching
     * @example 'div' matches <div />
     */
    case TYPE_SELECTOR:
      return nodeHasType(node, token.name);
    /**
     * Match against the `id` prop
     * @example '#nav' matches <ul id="nav" />
     */
    case ID_SELECTOR:
      return nodeHasId(node, token.name);
    /**
     * Matches if an attribute is present, regardless
     * of its value
     * @example '[disabled]' matches <a disabled />
     */
    case ATTRIBUTE_PRESENCE:
      return matchAttributeSelector(node, token);
    /**
     * Matches if an attribute is present with the
     * provided value
     * @example '[data-foo=foo]' matches <div data-foo="foo" />
     */
    case ATTRIBUTE_VALUE:
      return matchAttributeSelector(node, token);
    case PSEUDO_ELEMENT:
    case PSEUDO_CLASS:
      return matchPseudoSelector(node, token, root);
    default:
      throw new Error(`Unknown token type: ${token.type}`);
  }
}
1232052
def find_replace(self, node):
    """"""
    if isinstance(node, nodes.reference) and 'refuri' in node:
      r = node['refuri']
      if r.endswith('.md'):
        r = r[:-3] + '.html'
        node['refuri'] = r
      else:
        match = anchor_regex.match(r)
        if match:
          node['refuri'] = '{0:s}.html#{1:s}'.format(
              match.group('uri'), match.group('anchor'))
    return node
984519
public IEdge connect(INode source, INode target, VFBondMatcher matcher) {
        NodeBuilder sourceImpl = (NodeBuilder) source;
        NodeBuilder targetImpl = (NodeBuilder) target;
        EdgeBuilder edge = new EdgeBuilder(sourceImpl, targetImpl, matcher);

        sourceImpl.addNeighbor(targetImpl);
        targetImpl.addNeighbor(sourceImpl);

        sourceImpl.addEdge(edge);
        targetImpl.addEdge(edge);

        edgesList.add(edge);
        return edge;
    }
265431
function getMatchingElementFromMutation  (mutation, selector)
{
	let {
		type,
		target,
		addedNodes
	} = mutation;

	if (type === 'attributes' && target.matches(selector))
	{
		return target;
	}

	if (type === 'childList')
	{
		for (let addedNode of addedNodes)
		{
			if (typeof addedNode.matches === 'function' && addedNode.matches(selector))
			{
				return addedNode;
			}
		}

		return target.querySelector(selector);
	}

	return null;
}
1008776
function(node, pattern) {
		if (!!node && (node.nodeType === 3) && pattern.exec(node.nodeValue)) {
			node.nodeValue = node.nodeValue.replace(pattern, '');
		}
	}