本文介绍了在分隔字符串中,仅当子字符串与替换值匹配时,才在分隔符之间替换子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在分隔字符串中,仅当子字符串与替换值匹配时才在分隔符之间替换子字符串
I need to in a delimited string, replace substring between the delimiters only if the substring matches the replacement value
在Google表格中使用此
Using this in Google sheets
匹配
var ifind = ["AA", "CaaL"]; var ireplace = ["zz", "Bob"]; zz replaces AA Bob replaces CaaL我有
| Id | Segment | |----|--------------------| | 1 | AAA AA|AA|CaaL AA | | 2 | AAA-AA|AA|CaaL | | 3 | AAA, AA|AA|AA | | 4 | AA | | 5 | AA AA | | 6 | AA, AA | | 7 | | | 8 | CaaL | | 9 | AA |我需要
| Id | Segment | |----|-------------------| | 1 | AAA AA|zz|CaaL AA | | 2 | AAA-AA|zz|Bob | | 3 | AAA, AA|zz|zz | | 4 | zz | | 5 | AA AA | | 6 | AA, AA | | 7 | | | 8 | Bob | | 9 | zz |我已经尝试过(除其他事项外)
I have tried (amongst other things)
return [iFinds.reduce((str, k) => str.replace(new RegExp('\\b'+k+'\\b','g'),map[k]), input[0])]; and return [iFinds.reduce((str, k) => str.replace(new RegExp('(?![ .,]|^)?(\\b' + k + '\\b)(?=[., ]|$)','g'),map[k]), input[0])]; and return [iFinds.reduce((str, k) => str.split(k).join (map[k]), input[0])];我的功能(来自此处)
function findReplace_mod1() { const ss = SpreadsheetApp.getActiveSheet(); const col = ss.getRange(2, 3, ss.getLastRow()).getValues(); var ifind = ["AA", "Caal"]; var ireplace = ["zz", "Bob"]; var map = {}; ifind.forEach(function(item, i) { map[item] = ireplace[i]; }); //const map = { Fellow: 'AAA', bob: 'BBB' }; const iFinds = Object.keys(map); ss.getRange(2, 3, ss.getLastRow()).setValues(col.map(fr)); function fr(input) { return [iFinds.reduce((str, k) => str.replace(k, map[k]), input[0])]; } }谢谢
推荐答案您的固定函数看起来像
function findReplace_mod1() { const ss = SpreadsheetApp.getActiveSheet(); const col = ss.getRange(2, 3, ss.getLastRow()).getValues(); var ifind = ["AA", "CaaL"]; var ireplace = ["zz", "Bob"]; var map = {}; ifind.forEach(function(item, i) { map[item] = ireplace[i]; }); //const map = { Fellow: 'AAA', bob: 'BBB' }; const regex = new RegExp("(?<![^|])(?:" + ifind.join("|") + ")(?![^|])", "g"); ss.getRange(2, 3, ss.getLastRow()).setValues(col.map(fr)); function fr(input) { return input.map(c => c.replace(regex, (x) => map[x])); } }图案看起来像
/(?<![^|])(?:AA|CaaL)(?![^|])/g其中
- (?<![^ |])-是向后的否定式,如果存在 | 或紧接在左侧的字符串开头,则匹配失败当前位置的
- (?: AA | CaaL)-一个 AA 或 CaaL
- (?![^ |])-是负向的超前行为,如果在字符串的右边紧接有 | 或字符串结尾,则匹配失败.当前位置.
- (?<![^|]) - is a negative lookbehind that fails the match if there is a | or start of a string immediately to the left of the current location
- (?:AA|CaaL) - a AA or CaaL
- (?![^|]) - is a negative lookahead that fails the match if there is a | or end of a string immediately to the right of the current location.
请参见在线regex演示(由于该演示是针对单个多行字符串,而不是针对一组单独的字符串).
See the regex demo online (negative lookarounds are replaced with positive ones since the demo is run against a single multiline string, not a set of separate strings).
更多推荐
在分隔字符串中,仅当子字符串与替换值匹配时,才在分隔符之间替换子字符串
发布评论