Google sheet : REGEXREPLACE match everything except a particular pattern

蓝咒 提交于 2019-12-22 14:58:15

问题


I would try to replace everything inside this string :

[JGMORGAN - BANK2] n° 10 NEWYORK, n° 222 CAEN, MONTELLIER, VANNES / TARARTA TIs 1303222074, 1403281851 & 1307239335 et Cloture TIs 1403277567, 1410315029

Except the following numbers : 1303222074 1403281851 1307239335 1403277567 1410315029

I have built a REGEX to match them :

1[0-9]{9}

But I have not figured it out to do the opposite that is everything except all matches ...


回答1:


google spreadsheet use the Re2 regex engine and doesn't support many usefull features that can help you to do that. So a basic workaround can help you:

match what you want to preserve first and capture it:

pattern: [0-9]*(?:[0-9]{0,9}[^0-9]+)*(?:([0-9]{9,})|[0-9]*\z)

replacement: $1 (with a space after)

demo

So probably something like this:

=TRIM(REGEXREPLACE("[JGMORGAN - BANK2] n° 10 NEWYORK, n° 222 CAEN, MONTELLIER, VANNES / TARARTA TIs 1303222074, 1403281851 & 1307239335 et Cloture TIs 1403277567, 1410315029"; "[0-9]*(?:[0-9]{0,9}[^0-9]+)*(?:([0-9]{9,})|[0-9]*\z)"; "$1 "))



回答2:


Ok guys, first of all thank you Casimir for your help. It gaves me an idea : the idea that it will not be possible with a built-in functions of Google and a strong regex lol. So I found out that I can make my home made function for my own purpose (yes I'm not very "up to date" ...). So here is it (it is not very well coded and its returns doublons. But rather than fixing it properly, I use the built in UNIQUE() function on top of if to get rid of them, so yes it's ugly and i'm lasy but it does the job, that is, a list of all matches of on specifi regex (which is : 1[0-9]{9}) :

function ti_extract(input) {
  var tab_tis = new Array();
  var tab_strings = new Array();


  tab_tis.push(input.match(/1[0-9]{9}/));

  var string_modif = input.replace(tab_tis[0], " ");
  tab_strings.push(string_modif);

  var v = 0;
  var patt = new RegExp(/1[0-9]{9}/);
  var fin = patt.test(tab_strings[v]);

  var first_string = tab_strings[v];


  do {
    first_string = tab_strings[v]; // string 0
    tab_tis.push(first_string.match(/1[0-9]{9}/));

    var string_modif2 = first_string.replace(tab_tis[v], " ");
    tab_strings.push(string_modif2);

    v += 1;
  }
  while(v < 15)

  return tab_tis;
}



回答3:


You can also do this with dynamic native functions:

=REGEXEXTRACT(A1,rept("(\d{10}).*",counta(split(regexreplace(A1,"\d{10}","@"),"@"))-1))

basically it is first split by the desired string, to figure out how many occurrences there are of it, then repeats the regex to dynamically create that number of capture groups, thus leaving you in the end with only those values.



来源:https://stackoverflow.com/questions/28775466/google-sheet-regexreplace-match-everything-except-a-particular-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!