Mysql
 sql >> Database >  >> RDS >> Mysql

Come estrarre due cifre consecutive da un campo di testo in MySQL?

Se desideri una maggiore potenza delle espressioni regolari nel tuo database, puoi considerare l'utilizzo di LIB_MYSQLUDF_PREG . Questa è una libreria open source di funzioni utente MySQL che importa la libreria PCRE. LIB_MYSQLUDF_PREG viene fornito solo sotto forma di codice sorgente. Per usarlo, dovrai essere in grado di compilarlo e installarlo nel tuo server MySQL. L'installazione di questa libreria non modifica in alcun modo il supporto regex integrato di MySQL. Rende semplicemente disponibili le seguenti funzioni aggiuntive:

PREG_CAPTURE estrae una corrispondenza regolare da una stringa. PREG_POSITION restituisce la posizione in cui un'espressione regolare corrisponde a una stringa. PREG_REPLACE esegue una ricerca e sostituzione su una stringa. PREG_RLIKE verifica se una regex corrisponde a una stringa.

Tutte queste funzioni prendono un'espressione regolare come primo parametro. Questa espressione regolare deve essere formattata come un operatore di espressione regolare Perl. Per esempio. per verificare se regex corrisponde insensibile alle maiuscole e minuscole, dovresti utilizzare il codice MySQL PREG_RLIKE('/regex/i', subject). Questo è simile alle funzioni preg di PHP, che richiedono anche i // delimitatori extra per le espressioni regolari all'interno della stringa PHP.

Se desideri qualcosa di più semplice, puoi modificare questa funzione per adattarla meglio alle tue esigenze.

CREATE FUNCTION REGEXP_EXTRACT(string TEXT, exp TEXT)
-- Extract the first longest string that matches the regular expression
-- If the string is 'ABCD', check all strings and see what matches: 'ABCD', 'ABC', 'AB', 'A', 'BCD', 'BC', 'B', 'CD', 'C', 'D'
-- It's not smart enough to handle things like (A)|(BCD) correctly in that it will return the whole string, not just the matching token.

RETURNS TEXT
DETERMINISTIC
BEGIN
  DECLARE s INT DEFAULT 1;
  DECLARE e INT;
  DECLARE adjustStart TINYINT DEFAULT 1;
  DECLARE adjustEnd TINYINT DEFAULT 1;

  -- Because REGEXP matches anywhere in the string, and we only want the part that matches, adjust the expression to add '^' and '$'
  -- Of course, if those are already there, don't add them, but change the method of extraction accordingly.

  IF LEFT(exp, 1) = '^' THEN 
    SET adjustStart = 0;
  ELSE
    SET exp = CONCAT('^', exp);
  END IF;

  IF RIGHT(exp, 1) = '$' THEN
    SET adjustEnd = 0;
  ELSE
    SET exp = CONCAT(exp, '$');
  END IF;

  -- Loop through the string, moving the end pointer back towards the start pointer, then advance the start pointer and repeat
  -- Bail out of the loops early if the original expression started with '^' or ended with '$', since that means the pointers can't move
  WHILE (s <= LENGTH(string)) DO
    SET e = LENGTH(string);
    WHILE (e >= s) DO
      IF SUBSTRING(string, s, e) REGEXP exp THEN
        RETURN SUBSTRING(string, s, e);
      END IF;
      IF adjustEnd THEN
        SET e = e - 1;
      ELSE
        SET e = s - 1; -- ugh, such a hack to end it early
      END IF;
    END WHILE;
    IF adjustStart THEN
      SET s = s + 1;
    ELSE
      SET s = LENGTH(string) + 1; -- ugh, such a hack to end it early
    END IF;
  END WHILE;

  RETURN NULL;

END