Sandra Schlichting
Sandra Schlichting

Reputation: 26056

RegEx in MySQL?

When I do

SELECT resrev_meta FROM resourcerevs WHERE resrev_meta LIKE '%attr%';

I get results like this

<attr><fileid>131</fileid></attr> 
<attr><fileid>326</fileid><width>360</width><height>640</height></attr> 

Question

Is it possible to have a RegEx that would only output the number between <fileid> and </fileid>?

Upvotes: 1

Views: 153

Answers (3)

ZnArK
ZnArK

Reputation: 1539

Regex is probably not what your looking for. mysql supports xpath expressions.

This should give you what you need:

SELECT ExtractValue(resrev_meta,'//fileid')  AS fileid 
     FROM resourcerevs 
     WHERE resrev_meta LIKE '%attr%';

http://dev.mysql.com/doc/refman/5.1/en/xml-functions.html#function_extractvalue

mysql> SELECT
    ->   ExtractValue('<a>ccc<b>ddd</b></a>', '/a') AS val1,
    ->   ExtractValue('<a>ccc<b>ddd</b></a>', '/a/b') AS val2,
    ->   ExtractValue('<a>ccc<b>ddd</b></a>', '//b') AS val3,
    ->   ExtractValue('<a>ccc<b>ddd</b></a>', '/b') AS val4,
    ->   ExtractValue('<a>ccc<b>ddd</b><b>eee</b></a>', '//b') AS val5;

+------+------+------+------+---------+
| val1 | val2 | val3 | val4 | val5    |
+------+------+------+------+---------+
| ccc  | ddd  | ddd  |      | ddd eee |
+------+------+------+------+---------+

Upvotes: 5

Sean Bright
Sean Bright

Reputation: 120714

No, but you can do something hacky like this if you want (pardon the long lines):

SELECT
  SUBSTRING(
    resrev_meta,
    INSTR(resrev_meta, '<fileid>') + LENGTH('<fileid>'),
    INSTR(resrev_meta, '</fileid>') - INSTR(resrev_meta, '<fileid>') - LENGTH('<fileid>')) AS fileid
FROM resourcerevs WHERE resrev_meta LIKE '%attr%';

Upvotes: 3

Bohemian
Bohemian

Reputation: 425448

No, not using regex. Mysql doesn't support regex-based replacement or group matching etc.

The only regex support is RLIKE or REGEXP (they are synonyms), which is used to match a column value.

Upvotes: 3

Related Questions