简体   繁体   中英

regex: Match when between text but not between digits

Please help. I need a regular expression (to be used in javascript) to replace "." with "#" in a text containing Unicode characters. Replacement takes place only when "." appears between text but not between digits.

Input: "ΦΨ. ABC. DEF. 123.456"

Desired output: "ΦΨ# ABC# DEF# 123.456"

Any suggestions?

You can use capturing groups in the regex and use back-references to obtain the required result:

 var re = /(\\D)\\.(\\D)/g; var str = 'ΦΨ. ABC. DEF. 123.456'; var subst = '$1#$2'; result = str.replace(re, subst); alert(result); 

Regex Explanation:

  • \\D - A non-digit character
  • \\. - A literal dot

The non-digit characters are captured into groups, and then inserted back with the help of $1 and $2 back-references.

try this:

var str =  "ΦΨ. ABC. DEF. 123.456";

str.replace(/[^\d.]+\.[^\d]/g, function (m) {
    return m.replace('.', '#')
});

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