替换所有位置的字符串,除非它在引号内

Replace string everywhere except if its within quotes

本文关键字:位置 字符串 替换      更新时间:2023-09-26

我想用:D替换所有:),除非它们在引号"

示例1:

Hey man :D, how're you? :) My friend told me "this can't be true :)"

成为

Hey man :D, how're you? :D My friend told me "this can't be true :)"

如您所见,如果:)包含在"中,则它不会被替换。如果不存在这种情况,那就很简单了,对吧?我正在使用Javascript(jQuery(来完成这一切。

如果使用正则表达式显然无法做到这一点,那么还有什么其他建议呢?

假设没有双引号是不平衡的,这就是适用于您的正则表达式:

:')(?=(?:(?:[^"]*"){2})*[^"]*$)

解释:此正则表达式使用了一个正向前瞻,它基本上匹配一对some text until a double quote is found的0次或多次出现,即:)的每个匹配的右侧(RHS(上的([^"]*"){2}

简单来说,这意味着只有当:)在双引号外时才替换它,因为双引号内的所有匹配在RHS上都有奇数个[^"]*"匹配。

现场演示:1。http://www.rubular.com/r/3aixZy5bYR

现场演示:2。http://ideone.com/C679NW

function parseSmiley(str){
    return str.replace(/(?!"):')(?!")/g, ":D");
}
console.log(parseSmiley('Hey man :D, how''re you? :) My friend told me "this can''t be true :)"');

还有带输入的小提琴,这样你就可以测试了。

基本上,我们只是用:D 替换所有未封装在" "中的:)实例

如果你需要变量来控制它,那么你可以尝试

function doReplace(find, repl, str, fullWordsOnly, ignoreSQuotes,  ignoreDQuotes, caseSensitive) {
   if (caseSensitive == undefined) caseSensitive = false;
   var flags = 'gm';
   if (!caseSensitive) flags += 'i';
   var control = escapeRegExp(find);
   if (ignoreDQuotes) control = '(?!''B"[^"]*)' + control + '(?![^"]*"''B)';
   if (ignoreSQuotes) control = '(?!''B''[^'']*)' + control + '(?![^'']*''''B)';
   if (fullWordsOnly) control = '''b' + control + '''b';
   return str.replace(new RegExp(control, flags), repl);
}

注意,当使用缩写词(如how are和can't(时,这可能会出现单引号的问题,所以我还提供了一个破解方法:

// Fix any abbreviated words ('re or 't) 
str=str.replace(/'re'/b/gi, ''re');
str=str.replace(/'t'b/gi, ''t');

请参阅http://jsfiddle.net/Abeeee/ct7vayz5/4/对于工作演示