Posts

Showing posts with the label Replace

Can MySQL Replace Multiple Characters?

Answer : You can chain REPLACE functions: select replace(replace('hello world','world','earth'),'hello','hi') This will print hi earth . You can even use subqueries to replace multiple strings! select replace(london_english,'hello','hi') as warwickshire_english from ( select replace('hello world','world','earth') as london_english ) sub Or use a JOIN to replace them: select group_concat(newword separator ' ') from ( select 'hello' as oldword union all select 'world' ) orig inner join ( select 'hello' as oldword, 'hi' as newword union all select 'world', 'earth' ) trans on orig.oldword = trans.oldword I'll leave translation using common table expressions as an exercise for the reader ;) Cascading is the only simple and straight-forward solution to mysql for multiple character replacement. UPDATE table1...

Case-insensitive REPLACE In MySQL?

Answer : If replace(lower()) doesn't work, you'll need to create another function. My 2 cents. Since many people have upgraded from MySQL to MariaDB those people will have available a new function called REGEXP_REPLACE . Use it as you would a normal replace, but the pattern is a regular expression. This is a working example: UPDATE `myTable` SET `myField` = REGEXP_REPLACE(`myField`, '(?i)my insensitive string', 'new string') WHERE `myField` REGEXP '(?i)my insensitive string' The option (?i) makes all the subsequent matches case insensitive (if put at the beginning of the pattern like I have then it all is insensitive). See here for more information: https://mariadb.com/kb/en/mariadb/pcre/ Edit: as of MySQL 8.0 you can now use the regexp_replace function too, see documentation: https://dev.mysql.com/doc/refman/8.0/en/regexp.html Alternative function for one spoken by fvox. DELIMITER | CREATE FUNCTION case_insensitive_replace ( REPLA...

Can I Replace Groups In Java Regex?

Answer : Use $n (where n is a digit) to refer to captured subsequences in replaceFirst(...) . I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group. Pattern p = Pattern.compile("(\\d)(.*)(\\d)"); String input = "6 example input 4"; Matcher m = p.matcher(input); if (m.find()) { // replace first number with "number" and second number with the first String output = m.replaceFirst("number $3$1"); // number 46 } Consider (\D+) for the second group instead of (.*) . * is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d) has nothing to match, before it can match to the final digit. You could use Matcher#start(group) and Matcher#end(group) to build a generic replacement method: public static String replaceGroup(String regex, String source, int groupT...