简体   繁体   中英

Update a string using regular expressions in SQL

I have a string in my certain columns of my database:

<img title="\frac{3}{8}" src="http://latex.codecogs.com/gif.latex?\dpi{50}&amp;space;\fn_phv&amp;space;\frac{3}{8}" alt="" />

Basically it contains a html code for a fraction. But now I would like to replace it with:

<sup>3</sup>&frasl;<sub>8</sub>

I know I can update the value in the database as such:

UPDATE table 
SET `field` = Replace(`option`, '<img title="\frac{3}{8}" src="http://latex.codecogs.com/gif.latex?\dpi{50}&amp;space;\fn_phv&amp;space;\frac{3}{8}" alt="" />','<sup>3</sup>&frasl;<sub>8</sub>')
WHERE `filed` LIKE  '%<img title="\frac{3}{8}" src="http://latex.codecogs.com/gif.latex?\dpi{50}&amp;space;\fn_phv&amp;space;\frac{3}{8}" alt="" />%'

However, the word "\\frac{3}{8}" can change accordingly. The number in the parentheses can change and when it changes I need to change the html tag that will replace to change accordingly as well. I know I need to use regular expressions, but not sure how to do it in SQL.

Need some guidance to do it.

Why update the table? Why even have this stored in a table?

It seems like your application code (PHP?) could construct the string:

$numerator = 3;
$denominator = 8;
$img = "<img
      title="\frac{$numerator}{$denominator}"
      src=\"http://latex.codecogs.com/gif.latex?\dpi{50}&amp;
            space;\fn_phv&amp;space;\frac{$numerator}{$denominator}\"
      alt=''
      />";

(etc)

There is no REGEXP_REPLACE , except in MariaDB.

In MySQL, regular expressions are only supported for finding "matches", the REGEXP operator, which returns a boolean. There is no support for using regular expressions to return another value.

Reference: 12.5.2 Regular Expressions https://dev.mysql.com/doc/refman/5.6/en/regexp.html


You said that you " need to use regular expressions " to do string manipulation. That means you will have to extract the column values from the database into a client application, and perform the string manipulation in the client app. (From the client, issue an UPDATE statement to assign a new value to the column, replacing the existing value.)


EDIT

If you absolutely had to do this in a SQL statement, then one option is to create a user defined function that could be used to perform the string manipulation.

https://dev.mysql.com/doc/refman/5.6/en/adding-functions.html

It's possible someone has already coded one that does something similar to what you need. I don't want to give the impression that user-defined functions are a silver bullet; I mention it because it is an option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM