How to replace a regex pattern in MySQL

后端 未结 4 1206
感情败类
感情败类 2021-01-29 11:55

I have a table called myTable which has a column called col1. This column contains data in this format: (1 or 2 digits)(hyphen)(8 digits).

I wa

相关标签:
4条回答
  • 2021-01-29 12:24
    SELECT CONCAT( @new_prefix, SUBSTRING(old_value FROM LOCATE('-', old_value)) ) AS new_value
    

    UPDATE sourcetable
    SET fieldname = CONCAT( '4', SUBSTRING(fieldname FROM LOCATE('-', fieldname)) )
    WHERE LOCATE('-', fieldname)
    /* AND another conditions */
    
    0 讨论(0)
  • 2021-01-29 12:27

    You don't need regex; you can use SUBSTRING_INDEX to extract everything after the hyphen and concatenate 4- to that:

    UPDATE myTable
    SET col1 = CONCAT('4-', SUBSTRING_INDEX(col1, '-', -1))
    

    Demo on dbfiddle

    This will work regardless of the number of characters after the hyphen.

    0 讨论(0)
  • 2021-01-29 12:31

    Looking to your pattern seem you could avoid regexp

    update myTable  
    set col1  = concat('4-', right(col1,8))
    

    or

    update myTable  
    set col1  = concat('4', right(col1,9))
    
    0 讨论(0)
  • 2021-01-29 12:37

    Try this:

    UPDATE testing SET val=REPLACE(val,SUBSTRING(val,1,LOCATE('-',val)),'4-');
    

    Fiddle here :https://www.db-fiddle.com/f/4mU5ctLh8NB9iKSKZF9Ue2/2

    Using LOCATE to find '-' position then use SUBSTRING to get only the front part of the '-'.

    0 讨论(0)
提交回复
热议问题