2013-10-31 121 views
1

是否有任何方法可以捕获和替换引号中包含的字符串中的所有逗号,而不是引号外的任何逗号。我想改变他们的管道,然而这:替换带引号的字符串中的所有逗号

/("(.*?)?,(.*?)")/gm

仅获得第一个实例:

JSBIN

+0

你能给我们一些“之前和之后”的字符串,以便我们确定情况吗?例如,字符串中是否可以有多个双引号对,如果是这样,它是否应该替换所有这些对中的逗号? – talemyn

+0

@talemyn是的,那是真的。可能有多个带引号的字符串。 – 1252748

回答

5

如果回调是好的,你可以去这样的事情:

var str = '"test, test2, & test3",1324,,,,http://www.asdf.com'; 

var result = str.replace(/"[^"]+"/g, function (match) { 
    return match.replace(/,/g, '|'); 
}); 

console.log(result); 
//"test| test2| & test3",1324,,,,http://www.asdf.com 
+0

是可以使用'exec()'来实现这个而不是两个'replace()'。 MDN说我可以用它来对一个字符串运行一个模式多次,但我不明白如何。 – 1252748

+0

@thomas'exec'不会取代任何东西,所以您无论如何都需要这样做。如果你正在搜索*一个*正则表达式,[这个阅读](http://stackoverflow.com/questions/4476812/regular-expressions-how-to-replace-a-character-within-quotes?rq=1)可能会帮助你,但是,与PCRE相比,JS知道正常表达式有多糟糕(它缺乏很多向后看和向前看),那么它可能不起作用。 – h2ooooooo

0

与正则表达式版本相比,这是非常复杂的,但是,我想这样做,如果只是为了实验的目的:

var PEG = require("pegjs"); 

var parser = PEG.buildParser(
    ["start = seq", 
    "delimited = d:[^,\"]* { return d; }", 
    "quoted = q:[^\"]* { return q; }", 
    "quote = q:[\"] { return q; }", 
    "comma = c:[,] { return ''; }", 
    "dseq = delimited comma dseq/delimited", 
    "string = quote dseq quote", 
    "seq = quoted string seq/quoted quote? quoted?"].join("\n") 
); 

function flatten(array) { 
    return (array instanceof Array) ? 
     [].concat.apply([], array.map(flatten)) : 
     array; 
} 

flatten(parser.parse('foo "bar,bur,ber" baz "bbbr" "blerh')).join(""); 
// 'foo "barburber" baz "bbbr" "blerh' 

我不建议你这样做在这种特殊情况下,但也许它会创造出一些兴趣:)

PS。 pegjs可以在这里找到:(我不是一个作者,也没有从属关系,我只是喜欢PEG)http://pegjs.majda.cz/documentation

相关问题