Substituindo a enésima instância de uma correspondência regex em Javascript

StackOverflow https://stackoverflow.com/questions/36183

  •  09-06-2019
  •  | 
  •  

Pergunta

Estou tentando escrever uma função regex que identifique e substitua uma única instância de uma correspondência dentro de uma string sem afetar as outras instâncias.Por exemplo, eu tenho esta string:

12||34||56

Quero substituir o segundo conjunto de tubos por E comercial para obter esta string:

12||34&&56

A função regex precisa ser capaz de lidar com x quantidade de pipes e me permitir substituir o enésimo conjunto de pipes, para que eu possa usar a mesma função para fazer essas substituições:

23||45||45||56||67 -> 23&&45||45||56||67

23||34||98||87 -> 23||34||98&&87

Eu sei que poderia simplesmente dividir/substituir/concatenar a corda nos tubos, e também sei que posso combinar /\|\|/ e iterar pela matriz resultante, mas estou interessado em saber se é possível escrever uma única expressão que possa fazer isso.Observe que isso seria para Javascript, portanto é possível gerar uma regex em tempo de execução usando eval(), mas não é possível usar nenhuma instrução regex específica do Perl.

Foi útil?

Solução

aqui está algo que funciona:

"23||45||45||56||67".replace(/^((?:[0-9]+\|\|){n})([0-9]+)\|\|/,"$1$2&&")

onde n é menor que o enésimo tubo (é claro que você não precisa dessa primeira subexpressão se n = 0)

E se você quiser que uma função faça isso:

function pipe_replace(str,n) {
   var RE = new RegExp("^((?:[0-9]+\\|\\|){" + (n-1) + "})([0-9]+)\|\|");
   return str.replace(RE,"$1$2&&");
}

Outras dicas

Uma função de uso mais geral

Me deparei com esta pergunta e, embora o título seja muito geral, a resposta aceita trata apenas do caso de uso específico da pergunta.

Eu precisava de uma solução de uso mais geral, então escrevi uma e pensei em compartilhá-la aqui.

Uso

Esta função requer que você passe os seguintes argumentos:

  • original:a string que você está pesquisando
  • pattern:uma string para pesquisar ou um RegExp com um grupo de captura.Sem um grupo de captura, ocorrerá um erro.Isso ocorre porque a função chama split na string original, e somente se o RegExp fornecido contiver um grupo de captura a matriz resultante conterá as correspondências.
  • n:a ocorrência ordinal a ser encontrada;por exemplo, se você quiser a segunda partida, passe 2
  • replace:Uma string para substituir a correspondência ou uma função que receberá a correspondência e retornará uma string de substituição.

Exemplos

// Pipe examples like the OP's
replaceNthMatch("12||34||56", /(\|\|)/, 2, '&&') // "12||34&&56"
replaceNthMatch("23||45||45||56||67", /(\|\|)/, 1, '&&') // "23&&45||45||56||67"

// Replace groups of digits
replaceNthMatch("foo-1-bar-23-stuff-45", /(\d+)/, 3, 'NEW') // "foo-1-bar-23-stuff-NEW"

// Search value can be a string
replaceNthMatch("foo-stuff-foo-stuff-foo", "foo", 2, 'bar') // "foo-stuff-bar-stuff-foo"

// No change if there is no match for the search
replaceNthMatch("hello-world", "goodbye", 2, "adios") // "hello-world"

// No change if there is no Nth match for the search
replaceNthMatch("foo-1-bar-23-stuff-45", /(\d+)/, 6, 'NEW') // "foo-1-bar-23-stuff-45"

// Passing in a function to make the replacement
replaceNthMatch("foo-1-bar-23-stuff-45", /(\d+)/, 2, function(val){
  //increment the given value
  return parseInt(val, 10) + 1;
}); // "foo-1-bar-24-stuff-45"

O código

  var replaceNthMatch = function (original, pattern, n, replace) {
    var parts, tempParts;

    if (pattern.constructor === RegExp) {

      // If there's no match, bail
      if (original.search(pattern) === -1) {
        return original;
      }

      // Every other item should be a matched capture group;
      // between will be non-matching portions of the substring
      parts = original.split(pattern);

      // If there was a capture group, index 1 will be
      // an item that matches the RegExp
      if (parts[1].search(pattern) !== 0) {
        throw {name: "ArgumentError", message: "RegExp must have a capture group"};
      }
    } else if (pattern.constructor === String) {
      parts = original.split(pattern);
      // Need every other item to be the matched string
      tempParts = [];

      for (var i=0; i < parts.length; i++) {
        tempParts.push(parts[i]);

        // Insert between, but don't tack one onto the end
        if (i < parts.length - 1) {
          tempParts.push(pattern);
        }
      }
      parts = tempParts;
    }  else {
      throw {name: "ArgumentError", message: "Must provide either a RegExp or String"};
    }

    // Parens are unnecessary, but explicit. :)
    indexOfNthMatch = (n * 2) - 1;

  if (parts[indexOfNthMatch] === undefined) {
    // There IS no Nth match
    return original;
  }

  if (typeof(replace) === "function") {
    // Call it. After this, we don't need it anymore.
    replace = replace(parts[indexOfNthMatch]);
  }

  // Update our parts array with the new value
  parts[indexOfNthMatch] = replace;

  // Put it back together and return
  return parts.join('');

  }

Uma maneira alternativa de defini-lo

A parte menos atraente desta função é que ela leva 4 argumentos.Poderia ser simplificado para precisar de apenas 3 argumentos adicionando-o como um método ao protótipo String, assim:

String.prototype.replaceNthMatch = function(pattern, n, replace) {
  // Same code as above, replacing "original" with "this"
};

Se você fizer isso, poderá chamar o método em qualquer string, assim:

"foo-bar-foo".replaceNthMatch("foo", 2, "baz"); // "foo-bar-baz"

Passando nos testes

A seguir estão os testes Jasmine nos quais esta função passa.

describe("replaceNthMatch", function() {

  describe("when there is no match", function() {

    it("should return the unmodified original string", function() {
      var str = replaceNthMatch("hello-there", /(\d+)/, 3, 'NEW');
      expect(str).toEqual("hello-there");
    });

  });

  describe("when there is no Nth match", function() {

    it("should return the unmodified original string", function() {
      var str = replaceNthMatch("blah45stuff68hey", /(\d+)/, 3, 'NEW');
      expect(str).toEqual("blah45stuff68hey");
    });

  });

  describe("when the search argument is a RegExp", function() {

    describe("when it has a capture group", function () {

      it("should replace correctly when the match is in the middle", function(){
        var str = replaceNthMatch("this_937_thing_38_has_21_numbers", /(\d+)/, 2, 'NEW');
        expect(str).toEqual("this_937_thing_NEW_has_21_numbers");
      });

      it("should replace correctly when the match is at the beginning", function(){
        var str = replaceNthMatch("123_this_937_thing_38_has_21_numbers", /(\d+)/, 2, 'NEW');
        expect(str).toEqual("123_this_NEW_thing_38_has_21_numbers");
      });

    });

    describe("when it has no capture group", function() {

      it("should throw an error", function(){
        expect(function(){
          replaceNthMatch("one_1_two_2", /\d+/, 2, 'NEW');
        }).toThrow('RegExp must have a capture group');
      });

    });


  });

  describe("when the search argument is a string", function() {

    it("should should match and replace correctly", function(){
      var str = replaceNthMatch("blah45stuff68hey", 'stuff', 1, 'NEW');
      expect(str).toEqual("blah45NEW68hey");
    });

  });

  describe("when the replacement argument is a function", function() {

    it("should call it on the Nth match and replace with the return value", function(){

      // Look for the second number surrounded by brackets
      var str = replaceNthMatch("foo[1][2]", /(\[\d+\])/, 2, function(val) {

        // Get the number without the [ and ]
        var number = val.slice(1,-1);

        // Add 1
        number = parseInt(number,10) + 1;

        // Re-format and return
        return '[' + number + ']';
      });
      expect(str).toEqual("foo[1][3]");

    });

  });

});

Pode não funcionar no IE7

Este código pode falhar no IE7 porque o navegador divide incorretamente as strings usando um regex, conforme discutido aqui.[balança o punho para o IE7].Acredito que esse é a solução;se você precisar oferecer suporte ao IE7, boa sorte.:)

function pipe_replace(str,n) {
    m = 0;
    return str.replace(/\|\|/g, function (x) {
        //was n++ should have been m++
        m++;
        if (n==m) {
            return "&&";
        } else {
            return x;
        }
    });
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top