除非在引号内,否则将字符串替换到任何地方

时间:2013-04-01 09:55:36

标签: javascript regex string quotes

我想将所有:)替换为: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 个答案:

答案 0 :(得分:6)

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

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

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

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

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

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

答案 1 :(得分:-1)

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 :)"');

And the fiddle with an input so you can test

基本上,我们只是用[{1}}

替换:)中未包含" "的所有:D实例